Exception Handling
Short story
In my graduation there are two ways to go to my college, one is a main path and another one is alternative path. Generally i used to prefer main path on regularly to reach the college, but some times unexpectedly there may be a chance main path was full of traffic, then i used to prefer alternative path. So, my task is need to attend the college without fail.
- Case 1 : If no traffic then by main path, if i found traffic then by alternative path i have to go to college, here we can say task is terminated in normal way.
- Case 2 : If i found the traffic then sometimes without thinking i went to home directly instead of college, suppose that day if i have any exam in college which is not prepared, in this situation i went to home.Here we can say task is terminated in abnormal way.
Short story conclusion
- In our regular life if we are not able to go to main paths then we are choosing alternative paths to finish the task successfully.
- In Java also, if program execution is terminating abnormally then we need to handle the situation to finish the task in normal way.
Exception
- An unwanted unexpected event which disturbs the normal flow of the program is called an exception.
Exception Handling
- If program terminates abnormally then we need to find an alternative way to finish the rest of the program.
Advantage
- Might be exceptions will occur while coding, but ultimate goal is need to handle these exceptions to finish the task without fail by choosing any alternative ways.
- In my java coding career, i did not send any invitation card but most of the times NullPointerException used to come and sit in my coding.
- My Superior told as, with my experience i m suggesting just have a peaceful mind to handle this otherwise it takes your full day to fix.
- Then slowly by slowly i started discussion with Exception, even we had coffee each other at my desk after some time i heard Bye word from that Exception.
- Every Java developer may experience this Exception which will come and sit in our code without invitation.
Exception hierarchy
Program : Flow, if exception occured
--------------------------------------------------------------------------------------------
throws
Thanks for your time.
- Throwable class is the parent for Exception and Error.
Exception
- We can handle and resolve the exceptions, it will come in regular coding.
Error
- It might come due to the lack of system resources, we might not handle these.
Types of Exceptions
- Checked exception.
- Unchecked exception.
1. Checked exception
- Checked exception will come at the time of compiling the code.
- At compile time compiler will check these exceptions.
- Unchecked exception will come at run time.
- Runtime Exception and its child classes, Errors and its child classes are Unchecked Exceptions and all remaining are Checked Exceptions.
Chances to get Exceptions
--------------------------------------------------------------------------------------------
Program : ArithmeticException
Program name : ExcepDemo1.java
Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExcepDemo1.main(ExcepDemo1.java:5)
class ExcepDemo1
{
public static void main(String args[])
{
int a=50/0;
}
}
Compile : javac ExcepDemo1.java
Run : java ExcepDemo1
Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExcepDemo1.main(ExcepDemo1.java:5)
--------------------------------------------------------------------------------------------
Program : NullPointerException
Program name : ExcepDemo2.java
Output :
Exception in thread "main" java.lang.NullPointerException
at ExcepDemo2.main(ExcepDemo2.java:6)
class ExcepDemo2
{
public static void main(String args[])
{
String name = null;
System.out.println(name.length());
}
}
Compile : javac ExcepDemo2.java
Run : java ExcepDemo2
Output :
Exception in thread "main" java.lang.NullPointerException
at ExcepDemo2.main(ExcepDemo2.java:6)
--------------------------------------------------------------------------------------------
Handling Exceptions - By using try and catch blocks we can handle the exceptions.
try and catch
- try block follows either catch or finally.
- Inside try block we will keep only exception occurring code.
- Inside catch block we will keep only handling code for exception which is occurred in try block.
- catch block should be after try block only.
try
{
exception occurring code;
}
catch(Exception e)
{
Exception handling code
}
----------------------------------------------------------------------------
Program : Handling exception by using try and catch blocks
Program name : ExcepDemo3.java
Output :
25
class ExcepDemo3
{
public static void main(String args[])
{
try
{
int a=50/0;
}
catch(Exception e)
{
System.out.println(50/2);
}
}
}
Compile : javac ExcepDemo3.java
Run : java ExcepDemo3
Output :
25
--------------------------------------------------------------------------------------------
Program : Flow, if no exception
Program name : ExcepDemo4.java
Output :
Statement 1
Statement 2
Statement 3
Statement 4
Statement 5
class ExcepDemo4
{
public static void main(String args[])
{
System.out.println(“Statement 1”);
System.out.println(“Statement 2”);
System.out.println(“Statement 3”);
System.out.println(“Statement 4);
System.out.println(“Statement 5”);
}
}
Compile : javac ExcepDemo4.java
Run : java ExcepDemo4
Output :
Statement 1
Statement 2
Statement 3
Statement 4
Statement 5
--------------------------------------------------------------------------------------------
Bulletin points
- If any where else exception occurs then we need to handle the exception otherwise rest of the code will not execute. See the below program
Program name : ExcepDemo5.java
Output :
Statement 1
Statement 2
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExcepDemo5.main(ExcepDemo5.java:7)
class ExcepDemo5
{
public static void main(String args[])
{
System.out.println(“Statement 1”);
System.out.println(“Statement 2”);
System.out.println(10/0);
System.out.println(“Statement 4);
System.out.println(“Statement 5”);
}
}
Compile : javac ExcepDemo5.java
Run : java ExcepDemo5
Output :
Statement 1
Statement 2
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExcepDemo5.main(ExcepDemo5.java:7)
--------------------------------------------------------------------------------------------
Program : Flow, if exception occured and handled by try and catch
Program name : ExcepDemo6.java
Output :
Statement 1
Statement 2
Statement 3
Statement 4
Statement 5
class ExcepDemo5
{
public static void main(String args[])
{
System.out.println(“Statement 1”);
System.out.println(“Statement 2”);
try
{
try
{
System.out.println(15/0);
}
catch(Exception e)
{
System.out.println(15/5);
}
}
catch(Exception e)
{
System.out.println(15/5);
}
System.out.println(“Statement 4);
System.out.println(“Statement 5”);
}
}
Compile : javac ExcepDemo6.java
Run : java ExcepDemo6
Output :
Statement 1
Statement 2
Statement 3
Statement 4
Statement 5
--------------------------------------------------------------------------------------------
Multiple catch blocks
- We know well an exceptin will occur in a java statement and catch block will maintain the handling code.
- Sometimes there may be chance a java statement may raise group of exceptions then we need to maintain multiple catch blocks to handle the corresponding exceptions.
- At a time only one exception is occured for that single corresponding catch block will be executed.
- If multiple catch blocks exists in program then the order will be from child to parent.
--------------------------------------------------------------------------------------------
Program :
Sample program on multiple catch blocks
Program name:
ExcepDemo6.java
Output
:
ArithmeticException handled
Out of try and catch block
class ExcepDemo6
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[100]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException
handled");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException
handled");
}
catch(Exception e)
{
System.out.println("Exception
handled");
}
System.out.println("Out
of try and catch block");
}
}
Compile
: javac ExcepDemo6.java
Run
: java ExcepDemo6
Output
:
ArithmeticException handled
Out of try and catch block
--------------------------------------------------------------------------------------------
Nested try block
- try block within a try block is called as nested try block.
Syntax
try
{
statement 1;
statement 2;
try
{
statement 3;
statement 4;
}
catch (Exception e)
{
}
}
catch (Exception e)
{
}
--------------------------------------------------------------------------------------------
finally
- The finally block is always executed.
- If no exception then finally block will excute.
- If exception occurs and handled then finally block will execute.
- If exception occurs and not handled corresponding then finally block will execute.
- It is used to do cleanup operations like file closing and database connection closing operations.
- Before terminating the program, JVM will execute the finally block.
--------------------------------------------------------------------------------------------
Program :
If no exception then finally block will execute.
Program name:
ExcepDemo7.java
Output
:
try block executed
finally block is always executed
rest of the code...
class ExcepDemo7
{
public static void main(String args[])
{
try
{
System.out.println(“try block executed”);
}
catch(NullPointerException e)
{
System.out.println(“catch
block executed”);
}
finally
{
System.out.println("finally
block is always executed");
}
System.out.println("rest of the code...");
}
}
Compile
: javac ExcepDemo7.java
Run
: java ExcepDemo7
Output
:
try block executed
finally block is always executed
rest of the code...
--------------------------------------------------------------------------------------------
Program :
If exception occurred and handled then finally block will execute.
Program name:
ExcepDemo8.java
Output
:
try block executed
finally block is always executed
rest of the code...
class ExcepDemo8
{
public static void main(String args[])
{
try
{
System.out.println(“try block executed”);
System.out.println(25/0);
}
catch(ArithmeticException e)
{
System.out.println(“catch
block executed”);
}
finally
{
System.out.println("finally
block is always executed");
}
System.out.println("rest of the code...");
}
}
Compile
: javac ExcepDemo8.java
Run
: java ExcepDemo8
Output
:
try block executed
finally block is always executed
rest of the code...
--------------------------------------------------------------------------------------------
Program : If exception occurred and not handled corresponding then finally block will execute.
Program name: ExcepDemo9.java
Output
:
try block executed
finally block is always executed
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at ExcepDemo9.main(ExcepDemo9.java:8)
class ExcepDemo9
{
public static void main(String args[])
{
try
{
System.out.println(“try block executed”);
System.out.println(25/0);
}
catch(NullPointerException e)
{
System.out.println(“catch block executed”);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Compile : javac ExcepDemo9.java
Run : java ExcepDemo9
Output
:
try block executed
finally block is always executed
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at ExcepDemo9.main(ExcepDemo9.java:8)
--------------------------------------------------------------------------------------------
throw
- Some times programmer can create exception object and will submit that object to JVM explicitely by using throw keyword.
- The throw keyword is mainly used to throw custom exception
--------------------------------------------------------------------------------------------
Program :
ArithmeticException Demo
Program name:
ExcepDemo10.java
Output
:
Exception in thread "main" java.lang.ArithmeticException:
/ by zero
at ExcepDemo10.main(ExcepDemo10.java:5)
class ExcepDemo10
{
public static void main(String args[])
{
System.out.println(10/0);
}
}
Compile
: javac ExcepDemo10.java
Run
: java ExcepDemo10
Output
:
Exception in thread "main" java.lang.ArithmeticException:
/ by zero
at ExcepDemo10.main(ExcepDemo10.java:5)
--------------------------------------------------------------------------------------------
- In this case we created ArithmeticException object and submitted to JVM by using throw keyword
Program : ArithmeticException Demo
Program name: ExcepDemo11.java
Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExcepDemo11.main(ExcepDemo11.java:5)
class ExcepDemo11
{
public static void main(String args[])
{
throw new ArithmeticException("/ by zero");
}
}
Compile : javac ExcepDemo11.java
Run : java ExcepDemo11
Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExcepDemo11.main(ExcepDemo11.java:5)
--------------------------------------------------------------------------------------------
Customized Exceptions by using throw keyword
throws
- Some times programmer can use throws keyword to give responsibility of exception handling to the caller method.
--------------------------------------------------------------------------------------------
We can handle this by using the following two ways
Program : IOException Demo
Program name: ExcepDemo12.java
Output :
ExcepDemo12.java:9: error:
unreported exception IOException; must be caught or declare
d
to be thrown
name=br.readLine();
^
import java.io.*;
class Demo
{
String name;
public void accept()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter Name:”);
name=br.readLine();
}
public void display()
{
System.out.println(“Name:”+name);
}
}
class ExcepDemo12
{
public static void main(String args[])
{
Demo d=new Demo();
d.accept();
d.display();
}
}
Compile
: javac ExcepDemo12.java
Run
: java ExcepDemo12
Output
:
ExcepDemo12.java:9: error:
unreported exception IOException; must be caught or declare
d
to be thrown
name=br.readLine();
^
--------------------------------------------------------------------------------------------
- by using try catch block
- by using throws keyword
Program : Handling IOException by throws keyword
Program name: ExcepDemo12.java
Output :
Enter Name:
Nireekshan
Name:Nireekshan
import java.io.*;
class Demo
{
String name;
public void accept() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter Name:”);
name=br.readLine();
}
public void display()
{
System.out.println(“Name:”+name);
}
}
class ExcepDemo12
{
public static void main(String args[]) throws IOException
{
Demo d=new Demo();
d.accept();
d.display();
}
}
Compile : javac ExcepDemo12.java
Run : java ExcepDemo12
Output :
Enter Name:
Nireekshan
Name:Nireekshan
--------------------------------------------------------------------------------------------
Difference between throw and throws
--------------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan