Exception Handling in Java
Exception Handling in Java
Exception Handling in Java
1
What is Exception in Java
Dictionary Meaning: Exception is an abnormal
condition.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by
zero rest of the code...
} Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will
not be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
Example 2
public class TryCatchExample2 {
} Output:
java.lang.ArithmeticException: / by zero rest of the code
Now, as displayed in the above example, the rest of the code is executed,
i.e., the rest of the code statement is printed.
Java catch multiple exceptions
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java finally block
Java finally block is a block that
is used to execute important
code such as closing connection,
stream etc.
Java finally block is always
executed whether exception is
handled or not.
Java finally block follows try or
catch block.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Java throws keyword