0% found this document useful (0 votes)
17 views

Exception Handling

this ppt does into exception handling in Java

Uploaded by

aaryansh2003
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Exception Handling

this ppt does into exception handling in Java

Uploaded by

aaryansh2003
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

Exceptions Handling

Exceptions
 An exception is an object that describes an unusual or erroneous situation.
 Exceptions are thrown by a program and may be caught and handled by another
part of the program.
 (Dictionary Meaning: Exception is an abnormal condition).
 In Java, an exception is an event that disrupts the normal flow of
the program. It is an object which is thrown at runtime.
 Advantage of Exception Handling
 The core advantage of exception handling is to maintain the
normal flow of the application. An exception normally disrupts
the normal flow of the application; that is why we need to handle
exceptions.
Exception Hierarchy
 Errors:
 Errors are fairly rare and usually fatal. They are
caused by bugs in the Java VM, or by the
program running out of memory or other
resources.
 Errors are usually not handled by programs.
 Exceptions:
 Exceptions can be caused by bugs in the
program or improper data supplied to the
program
 Exceptions should be handled, or caught
 An exception is either checked or unchecked
 Checked exceptions must be caught or declared
as thrown.
Attack of the Exception

public class Exception1 {  What happens when this


public static void main (String [] method is used to divide 60
args) { by the array elements ?
int a[]={10,20,30,0,50,60};  Program throws an
for(int i=0;i<a.length;i++)
{ Exception and fails
float y=60/a[i];
System.out.println(y); java.lang.Arithmet
icException: / by
}
zero
}
What is an Exception?
 An error event that disrupts the program flow and may cause a program
to fail.
 Some examples:
 Performing illegal arithmetic
 Illegal arguments to methods
 Accessing an out-of-bounds array element
 Hardware failures
 Writing to a read-only file
Another Exception Example
 What is the output of this program?
public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}

Output:
Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
 What exception class? ArrayIndexOutOfBoundsException
 Which array index is out of bounds? 2
 What method throws the exception? main
 What file contains the method? ExceptionExample.java
 What line of the file throws the exception? 4
Classifying Java Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class

except RuntimeException and Error are known as checked


exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known

as unchecked exceptions. For example,


ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are
checked at runtime.
Classifying Java Exceptions
 Unchecked Exceptions
 All the exceptions we've seen so far have been Unchecked Exceptions, or
Runtime Exceptions
 Usually occur because of programming errors, when code is not robust enough to
prevent them
 They are numerous and can be ignored by the programmer
 Common Unchecked Exceptions

NullPointerException: reference is null .

IllegalArgumentException: method argument is improper

IllegalStateException: method called when class is in improper state

9
 Checked Exceptions
 Usually occur because of errors, programmer cannot control it.

examples: hardware failures, unreadable files
 They are less frequent, and they cannot be ignored by the programmer . . .
 Every method must catch (handle) checked exceptions or specify that it may throw
them
 Specify with the throws keyword
Checked and Unchecked Exceptions
Checked Exception Unchecked Exception

not subclass of RuntimeException subclass of RuntimeException


if not caught, method must specify it to be if not caught, method may specify it to be
thrown thrown
for errors that the programmer cannot directly for errors that the programmer can directly
prevent from occurring prevent from occurring,

IOException, FileNotFoundException, NullPointerException,


SocketException IllegalArgumentException,
IllegalStateException
Exception Class Hierarchy
 All exceptions are instances of classes that are subclasses
of Exception
Exception

RuntimeException IOException SQLException

ArrayIndexOutofBounds FileNotFoundException

NullPointerException MalformedURLException

IllegalArgumentException SocketException

etc. etc.

Unchecked Exceptions Checked Exceptions


Keywords for Java Exceptions
 throws: - The "throws" keyword is used to declare exceptions. It
specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method
signature.
 throw: - Raises an exception to the first available handler in the call stack,
unwinding the stack along the way.
 try: - The "try" keyword is used to specify a block where we
should place an exception code. It means we can't use try block
alone. The try block must be followed by either catch or finally.
 catch: - If the block enclosed by the try generates an exception of this type,
control moves here.
 finally: - Always called when the try block concludes, and after any necessary
catch handler is complete.
13
Exceptions Terminology
 When an exception happens we say it was thrown or raised
 When an exception is dealt with, we say the exception is handled or
caught
Exception Handling (Try and Catch )
 Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Internal Working of Java try-catch block
Example of Exception
public class Exception1 {
public static void main
(String [] args) {
int a[]={10,20,30,0,50,60};
for(int i=0;i<a.length;i++)
{
float y=60/a[i];
System.out.println(y);

}
}
Example of Exception
public class Exception1 {
public class Exception1 { public static void main (String []
public static void main args) {
(String [] args) { int a[]={10,20,30,0,50,60};
for(int i=0;i<a.length;i++)
int a[]={10,20,30,0,50,60}; {
for(int i=0;i<a.length;i++) try
{
{ float y=60/a[i];
float y=60/a[i]; System.out.println(y);
}
System.out.println(y);
catch(Exception e)
{
}
System.out.println("invalid
} division");
}
}

System.out.println("you are out of the


program");
AirthmeticException
 class Exc2 {
 public static void main(String args[]) {
 int d, a;
 try { // monitor a block of code.
 d = 0;
 a = 42 / d;
 System.out.println("This will not be printed.");
 } catch (ArithmeticException e) { // catch divide-by-zero error
 System.out.println("Division by zero.");
 }
Multiple Catch Clauses
 In some cases, more than one exception could be raised
by a single piece of code.
 To handle this type of situation, you can specify two or
more catch clauses, each catching a different type of
exception.
 When an exception is thrown, each catch statement is
inspected in order, and the first one whose type matches
that of the exception is executed.
 After one catch statement executes, the others are
bypassed, and execution continues after the try / catch
block
Catching Multiple Exceptions
 Handle multiple possible exceptions by multiple successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
Example of Multiple Catch Clauses
// Demonstrate multiple catch statements.
class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
Nested Try Statement
// An example of nested try if(a==2) {
statements. int c[] = { 1 };
class NestTry { c[42] = 99; // generate an out-of-
public static void main(String args[]) { bounds exception
}
try { }
int a = args.length; catch(ArrayIndexOutOfBoundsExcep
int b = 42 / a; tion e) {
System.out.println("a = " + a); System.out.println("Array index out-
of-bounds: " + e);
try { // nested try block
}
if(a==1) a = a/(a-a); // division by zero } catch(ArithmeticException e) {
System.out.println("Divide by 0: " +
e);
}}}
Throw
 So far, you have only been catching exceptions that are thrown by the
Java run-time system. However, it is possible for your program to throw
an exception explicitly, using the throw statement.

 The general form of throw is shown here:


 throw ThrowableInstance;

 Here, ThrowableInstance must be an object of type Throwable or a


subclass of Throwable. Primitive types, such as int or char, as well as
non-Throwable classes, such as String and Object, cannot be used as
exceptions. There are two ways you can obtain a Throwable object:
using a parameter in a catch clause or creating one with the new
operator
Example Throw
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}}}
throws Clause
 If a method is capable of causing an exception that it does not handle, it must
specify this behavior so that callers of the method can guard themselves
against that exception.
 You do this by including a throws clause in the method’s declaration. A
throws clause lists the types of exceptions that a method might throw.
 This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
 Here, exception-list is a comma-separated list of the exceptions that a method
can throw.
throws Clause

Example:

class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
} }
throws Clause

Example 3:

class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
} Output:
} inside throwOne
} caught
java.lang.IllegalAccessExcepti
on: demo
finally
 If the try block is executed, then the finally block is guaranteed to be
executed, regardless of whether any catch block was executed.
 Since the finally block is always executed before control transfers to its
final destination, the finally block can be used to specify any clean-up code
(e.g., to free resources such as files and net connections).
 The finally block will execute whether or not an exception is thrown.
finally

Example 3:

class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
finally{
System.out.println(" finally executed");
}
} }
finally

Example 3:
class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
finally{
System.out.println(" finally executed"); Output:
} inside throwOne
}
} caught
java.lang.IllegalAccessEx
ception: demo
finally executed
Built-In Exceptions
 Java defines several exception classes.
 The most general of these exceptions are subclasses of the standard type
RuntimeException.
 As previously explained, these exceptions need not be included in any
method’s throws list.
 These are called unchecked exceptions because the compiler does not
check to see if a method handles or throws these exceptions.
 The checked exceptions must be included in a method’s throws list if that
method can generate one of these exceptions and does not handle it itself.
 In addition to the exceptions in java.lang, Java defines several more that
relate to its other standard packages.
Built-In Exceptions
Throwable class:
The Throwable class is the superclass of all errors and exceptions in the

Java language.
Only objects that are instances of this class (or one of its subclasses) are

thrown by the Java Virtual Machine or can be thrown by the Java throw
statement.
Similarly, only this class or one of its subclasses can be the argument type in

a catch clause.
By convention, class Throwable and its subclasses have two constructors,

one that takes no arguments and one that takes a String argument that can be
used to produce a detail message.
Java’s Unchecked RuntimeException Subclasses
Defined in java.lang
Java’s Checked Exceptions Defined in java.lang
Creating Your Own Exception
 Although Java’s built-in exceptions handle most common errors.
 However, you will probably want to create your own exception types to
handle situations specific to your applications.
 To do just define a subclass of Exception.
 The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable.
 Exception defines four public constructors.
Creating Your Own Exception
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) { Called compute(1)
System.out.println("Caught " + e); Normal exit
} Called compute(20)
} Caught MyException[20]
}
Example 2 (Invalid Age )
// class representing custom exception // throw an object of user defined exception
throw new InvalidAgeException("age is not va
class InvalidAgeException extends Exception
lid to vote");
{ }
public InvalidAgeException (String str) else {
System.out.println("welcome to vote");
{ } }
// calling the constructor of parent Exception
super(str); // main method
public static void main(String args[]) {
} try
} {
// class that uses custom exception InvalidAgeEx // calling the method
validate(13);
ception
}
public class TestCustomException1 catch (InvalidAgeException ex)
{ {
System.out.println("Caught the exception");
// method to check the age
static void validate (int age) throws InvalidAg
eException{ // printing the message from InvalidAgeExcep
tion object
if(age < 18){
System.out.println("Exception occured: " + e
x);
}

You might also like