Exception Handling In java
Exception Handling in Java
Exception: Exceptions are the run-time errors in java . To handle these type of errors we come across the concept of "Exception Handling".
Exception will interrupt the flow of control of the program .
Exception can be of three types :
- Checked Exception
- Unchecked Exception
- Error.
Checked Exception: All the compile time exceptions are considered as Checked Exceptions.
These classes will extend the Throwable class.
Examples :(IO Exception, SQL Exceptions).
Un-checked Exception: All the Run time Exceptions are considered as Un Checked Exceptions.
These will extends RunTimeException Class .
Examples:(ArithmeticException, ArrayIndexOutOfBoundException).
Error: The Exceptions that cant be handled are called as Errors (will not be recovered).
Example: (OutOfMemory Error,VirtualMacine Error).
Arithmetic Exceptions : These type of exceptions occurs due to the incorrect mathematical operations .
Example:
A number divided by zero is gives infinity i.e... cant be defined hence it can be considered as Arithmetic Exceptions .
a=b/0;
Here this code raises an exception called arithmetic exception .
Null Pointer Exception : These type of exceptions occurs when we have a null variable and we are trying to perform any operation then raises Null Pointer Exception .
Example :
String str=null;
System.out.println(str.reverse());
These above example raises an exception called NullPointerException .
Number Format Exception : These type of exception occurs when we convert string type of data to any other type of data like integer or floating type .
Example:
String str="Void main ";
int i=Integer.parseInt(str);
From the above example string type cant be converted into the integer type hence it raises the Number Format Exception .
Array Index OuT oF Bound Exception : When we have an array of particular size and if we try to access or if we try to initialize the value out of given range of an array then it raises ArrayIndexOutOfBoundException .
Example :
int a[10];
a[20]=500;
In the above example the declared size of an array is 10 but we have initialized with a size of 20 hence it raises ArrayIndexOutOfBoundException .
Programs on Exceptions Raised by jvm :
import java.util.*;
class ExceptionsByJvm
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two values");
int a=sc.nextInt();
int b=sc.nextInt();
double c=a/b;
System.out.println("The division is :"+c);
}
}
Save As :
ExceptionsByJvm .java
Compile :
javac ExceptionsByJvm .java
Run :
java ExceptionsByJvm
Input :
Enter two values :
10
0
Output:
Exception in thread "main" java.lang.ArithmeticException : / by zero at ExceptionByJvm.main<ExceptionByJvm.java: 15>
Note :
The error or the exception raised in the above can be understandable for the java developers but cant be understand easily by the user . so to avoid this problems for the user we come across the concept of "EXCEPTION HANDLING".
By using Exception Handling we can make the predefined exception to user defined or user understandable exceptions .
To handle this and convert the pre defined exceptions to user defined exceptions we come across 5 blocks in Exception handling namely as follows :
- try
- catch
- throw
- throws
- finally.
These blocks are described clearly as follows :
try block :
try is a keyword in java and represented by small letters and this is used to handle the exceptions raised by the set of code .
Here we have to place the code which generates the exception in try block such that if there is any exception it automatically moves to catch block were we can convert the predefined exception to user defined exceptions .
Syntax:
try
{
the code were there is chance of raising exception;
}
Program using try block
import java.util.*;
class ExceptionsTryBlock
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two values");
int a=sc.nextInt();
int b=sc.nextInt();
try
{
double c=a/b;
}
System.out.println("The division is :"+c);
}
}
Save As :
ExceptionsTryBlock .java
Compile :
javac ExceptionsTryBlock .java
Run :
java ExceptionsTryBlock
Input :
Enter two values :
10
0
Output:
Exception in thread "main" java.lang.ArithmeticException : / by zero at ExceptionByJvm.main<ExceptionByJvm.java: 15>
Note:
By seeing the above output we get a doubt that it has same output as before , reason for this is that every try block must be succeeded with either a catch or finally block otherwise compiler cant handle the errors or the exceptions raised .
Hence we have to use either a catch or finally block followed by try block .
catch block :
This block is followed by try block it contains a parameter which can take the predefined class object as parameter and this block is executed only when there is any exception raised in try block .
whenever there is an exception raised in try block the cursor automatically moves to catch block otherwise it execution skips catch block .
Syntax:
try
{
code were there is a chance of raising exception;
}
catch(<ExceptionclassName> <objectName>)
{
exception to be displayed for the user to understand;
}
Program using catch block
import java.util.*;
class ExceptionsCatchBlock
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two values");
int a=sc.nextInt();
int b=sc.nextInt();
double c=0;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("U have entered zero value in the denominator ");
}
System.out.println("The division is :"+c);
}
}
Save As :
ExceptionsCatchBlock .java
Compile :
javac ExceptionsCatchBlock.java
Run:
java ExceptionsCatchBlock
Input :
Enter two values :
10
0
Output :
U have entered zero value in the denominator
The division is : 0.0
Note :
A single try block can have any number of catch blocks but with different Exception class objects as parameters .
The Exception class object must be placed in last catch block . Since it is the super class of all the other exception classes .
Program using multiple catch blocks
import java.util.*;
class ExceptionsMultipleCatch
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two values");
int a=sc.nextInt();
int b=sc.nextInt();
double c=0;
String str=null;
try
{
c=a/b;
System.out.println(str.length());
}
catch(ArithmeticException e)
{
System.out.println("U have entered zero value in the denominator ");
}
catch(NullPointerException e)
{
System.out.println("Null Pointer Exception");
}
System.out.println("The division is :"+c);
}
}
Save As:
ExceptionsMultipleCatch .java
Compile :
javac ExceptionsMultipleCatch .java
Run :
java ExceptionsMultipleCatch
Input :
Enter two values :
20
10
Output:
Null Pointer Exception
The Division is : 2.0
Note :
In the above program we have only one try block and two catch blocks . When there is arithmetic exception in the try block it moves to Arithmetic exception catch block .
If there is any Null Pointer Exception then it moves to the second catch block and executes that block .
If there is no exception in the try block it automatically skips both catch blocks.
Finally Block : As we discussed previously that a try block may be succeeded with either a catch or finally block .
Syntax:
try
{
code which may raise the exception must be written here in this block ;
}
finally
{
compulsory executable statements must be placed here ;
}
Program using finally block
import java.util.*;
class ExceptionsFinallyBlock
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two values");
int a=sc.nextInt();
int b=sc.nextInt();
double c=0;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("U have entered zero value in the denominator ");
}
finally
{
System.out.println("Thank you");
}
System.out.println("The division is :"+c);
}
}
Save As:
ExceptionsFinallyBlock.java
Compile :
javac ExceptionsFinallyBlock.java
java ExceptionsFinallyBlock
Input :
Enter Two values :
20
0
Output :
U have entered zero value in the denominator
Thank you // From finally block
The division is : 0.0 // After handling the exception
Note :
Even we can use finally block alone with try or we can use finally with try-catch block .
When we use try, catch, finally block then try sequence followed is try-catch then finally , Otherwise compilation error .
Each program can have only one finally block and will be executed only once . There should not be any lines of code between try-catch and finally block . if present compilation error .
Syntax :
throw exception ;
throw block :
Here these are used to throw the custom exception .It is used to throw both checked and unchecked exceptions . These are used to throw the exceptions explicitly .Syntax :
throw exception ;
Program for throw block
class ExceptionsThrowBlock
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter two values ");
int a=sc.nextInt();
int b=sc.nextInt();
if(a<b)
{
throw new ArithmeticException("a is lesser than b ");
}
else
{
System.out.println("b is greater than a ");
}
}
}
Save As:
ExceptionsThrowBlock.java
Compile :
javac ExceptionsThrowBlock.java
Run :
java ExceptionsThrowBlock
Input :
enter two values
10
20
Output:
a is lesser than b //by throw statements
Note :
By using throw we can know the type of exception as well as user defined exception .
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter two values ");
int a=sc.nextInt();
int b=sc.nextInt();
if(a<b)
{
throw new ArithmeticException("a is lesser than b ");
}
else
{
System.out.println("b is greater than a ");
}
}
}
Save As:
ExceptionsThrowBlock.java
Compile :
javac ExceptionsThrowBlock.java
Run :
java ExceptionsThrowBlock
Input :
enter two values
10
20
Output:
a is lesser than b //by throw statements
Note :
By using throw we can know the type of exception as well as user defined exception .
throws :
it is a keyword used to handle the exceptions in java . It is used to handle the unchecked exceptions and here this will give the information to the programmer that the particular method will generate the unchecked exception .
Syntax:
void methodName() throws ExceptionClassName
{
statements ;
}
Program using throws keyword
import java.io.*;
class Throws
{
void throwsMethod() throws IOException
{
throw new IOException("this is throws block");
}
}
class ExceptionsThrowsBlock
{
public static void main(String[] args)
{
try
{
Throws t=new Throws();
t.throwsMethod();
}
catch (IOException e)
{
System.out.println("IO Exception is handled");
}
System.out.println("Out of exception block");
}
}
Save As :
ExceptionsThrowsBlock .java
Compile
javac ExceptionsThrowsBlock.java
Run :
java ExceptionsThrowsBlock
Output:
IO Exception is handled
Out of exception block
Flow of exception:
here when there is an exception in 1st method and not handled then it moves to the other method which calls the 1st method if it is not handled there also it moves to another method and continues until the exception is handled .
Program for Flow of Exception
import java.util.*;
class Flow
{
void method1(int a,int b)
{
int d=a/b;
}
void method2(int a,int b)
{
method1(a,b);
}
void method3(int a,int b)
{
try
{
method2(a,b);
}
catch (Exception e)
{
System.out.println("Arithmetic exception");
}
}
}
class ExceptionsFlow
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter two values ");
int a=sc.nextInt();
int b=sc.nextInt();
Flow f=new Flow();
f.method3(a,b);
}
}
Save As:
ExceptionsFlow.java
Compile :
javac
ExceptionsFlow.java
Run :
java
ExceptionsFlow
Input :
enter two values
10
0
Output:
Arithmetic exception
Note :
Here there is an exception in method1() where the exception is not handled then it ,moves to the method2() there also exception is not handled and hence moves to method3() where the exception is handled .
Nested try :
A try block within another try block is called as nested try . Here there may be a situation to check the exceptions even for a single block or entire block then at such situation we use nested try .
Syntax:
try
{
outside try;
try
{
inside try;
}
catch(ExceptionClass obj)
{
inner catch;
}
}
catch(Exception obj)
{
catch for outer try;
}
Program on nested try block
import java.util.*;
class ExceptionsNestedTry
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter two values");
int a=sc.nextInt();
int b=sc.nextInt();
try
{
try
{
int c=a/b;
System.out.println("the value of c:"+c);
}
catch (ArithmeticException ae)
{
System.out.println("Inner try block exception");
}
int aa[]=new int[5];
aa[5]=4;
}
catch (Exception e)
{
System.out.println("Outer try block exception");
}
}
}
Save As:
ExceptionsNestedTry.java
Compile As:
javac ExceptionsNestedTry.java
Run As:
java ExceptionsNestedTry
Input :
Enter two values
10
0
Output:
Inner try block exception
Outer try block exception.
Note :
Here when the exception raises in the inner try block it will go to the catch of inner block and if there no exception it wont goes to the inner catch block . It will execute the statements in the inner try block .
If there is any exception in outer try block it will execute the outer catch block but wont think about inner try block .
www.void Main Technologies.com

Comments
Post a Comment