Exception Handling in java is the powerful mechanism to handle run time errors in a java program.It is an abnormal condition in a program running cycle.
Mainly Exceptions are of checked and unchecked exceptions.
Advantages of Exceptions handling:
statement1;
statement2;
statement3; // Exception occurs
statement4;
Then the fourth statement will not execute, instead if we handled the exception then the next statement will execute.
Mainly Exceptions are of checked and unchecked exceptions.
Advantages of Exceptions handling:
statement1;
statement2;
statement3; // Exception occurs
statement4;
Then the fourth statement will not execute, instead if we handled the exception then the next statement will execute.
Types of exceptions:
As mentioned above there are two types of exceptions:
Checked and Unchecked Exceptions
Checked Exceptions:
The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions e.g.IOException, SQLException etc.
Checked exceptions are checked at compile-time.
Unchecked Exceptions:
The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked
at compile-time rather they are checked at runtime.
Common Scenarios for exceptions:
- int n=20/0;//ArithmeticException
- String a=null; System.out.println(a.length()); //NullPointerException
- String a="one"; int i=Integer.parseInt(a);//NumberFormatException
- int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
Implementing exceptions:
Java try-catch and Java try-finally blocks
Syntax of try- catch
- try{
- //code that may throw exception
- }
- catch(Exception_class_Name ref){
- }
Syntax of try-finally block
- try{
- //code that may throw exception
- }finally{}
Example1:
public class sample{
public static void main(String args[]){
try{
int n=20/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
public static void main(String args[]){
try{
int n=20/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Example2:
class sample2{
public static void main(String args[]){
try{
int n=45/5;
System.out.println(n);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
public static void main(String args[]){
try{
int n=45/5;
System.out.println(n);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Above mentioned above will give an idea on what is exceptions and exception handling in java.