Exception Handling
Exception Handling
As displayed in the above example, rest of the code is not executed (in such case,
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 above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Rule: All catch blocks must be ordered from most specific to most general
i.e. catch for ArithmeticException must come before catch for Exception .
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 must be followed by try or catch block.
Note: If you don't handle exception, before terminating the program, JVM
executes finally block(if any).
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Case 2
Let's see the java finally example where exception occurs and not
handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);}
finally{
System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
In this example, we have created the validate method that takes integer
value as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
throws keyword
The Java throws keyword is used to declare an exception. It gives
an information to the programmer that there may occur an exception
so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained.