Exception Handling
Exception Handling
• Output:
• Exception in thread main
java.lang.ArithmeticException:/ by zero
Hierarchical Structure of
Throwable Class
Definition of Exception
• Error Class
– Critical error which is not acceptable in
normal application program
• Exception Class
– Possible exception in normal application
program execution
– Possible to handle by programmer
Java’s Built-in Exceptions
● Inside the standard package java.lang, Java defines several
exception classes
[DivByZero.java]
System-Defined Exception
• IndexOutOfBoundsException :
– When beyond the bound of index in the object which use index, such as
array, string, and vector
• ArrayStoreException :
– When assign object of incorrect type to element of array
• NegativeArraySizeException :
– When using a negative size of array
• IOException:
– Caused by IO failiures.
• FileNotFoundException:
• IllegalMonitorStateException :
– When the thread which is not owner of monitor involves wait or notify
method
Programmer-Defined Exception
Exceptions raised by programmer
• Check by compiler whether the
exception handler for exception
occurred exists or not
– If there is no handler, it is error
Try-Catch Mechanism
● Handling exception by yourself provides 2 benefits.
First, it allows you to fix the error. Second, it prevents
the program from automatically terminating.
catch (ArithmeticException e) {
System.out.println("Division by zero."); }
System.out.println("After catch statement."); } }
catch (ArithmeticException e) {
System out println("Exception: " + e);
a = 0; // set a to zero and continue }
int b = 5;
int x=a[2] /b-a[1];}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e); }
catch(Exception e)
{System.out.println("common task completed");} }
Nested Try
● The try statement can be nested. That is, a try statement can be
• inside the block of another try.
• Sometimes a situation may arise where a part of a block may
cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.
try{
int a[]=new int[5];
a[0]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e
);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following
the try/catch block.
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main
java.lang.ArithmeticException:/ by zero finally block is
always executed rest of the code...
Throw
● Instead of Java Run-Time system, it is also possible for your program to
throw an exception explicitly, using the throw statement. The
general form of throw is shown here:
throw ExceptionObject;
Class Test
public static void main(String args[]) {
4)You cannot throw multiple exception You can declare multiple exception e.g.
public void method()throws
IOException,SQLException.
Exceptions fall into two categories:
Checked Exceptions
Unchecked Exceptions
1) Unchecked Exception
The exceptions that are not checked at compile time are called unchecked
exceptions, classes that extends RuntimeException comes under unchecked
exceptions.
2) CheckedExceptions
Exceptions that are checked at compile-time are called checked exceptions, in
Exception hierarchy all classes that extends Exception class except
UncheckedException comes under checked exception category.
try {
String input = reader.readLine();
System.out.println("You typed : "+input); // Exception prone area
}
catch (IOException e) {}
While writing a code to read or write something from files or even from or to
console, an checked Exception i.e. IOException is thrown, these exceptions are
checked at compile time and we are forced to write a handler at compile time.
That’s why we called these exceptions Checked Exceptions.
class FinallyDemo {// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {System.out.println("procA's finally");}} // 1st finally (after exception thrown)
catch (Exception e) {
System.out.println("Exception caught");}
procB();
procC();}}
Creating your own Exception
subclasses
● We can create our own exception
types to handle situations specific to your applications.
class ExceptionDemo{
public static void main(String args[]) {
try{
System.out.println("No Exception");}
catch (MyException e) {
System.out.println("Caught " + e);}}}
.Contd