x (Lec-27)Java SE(Exception Handling-1)
x (Lec-27)Java SE(Exception Handling-1)
(CORE JAVA)
LECTURE-27
Today’s Agenda
• Exception Handling
• Exception hierarchy
Exception Handling
2. catch
3. throw
4. throws
5. finally
try and catch
• Syntax:-
try Those lines on which an exception may occur
are written in the try block.
{
---
As soon as an exception occurs, java leaves the
--- try block and moves towards the catch block.
}
catch(<Exception class name> <object reference>)
{ Object reference points to that
--- object which is sent by the try block
after an exception occurs.
--- The class should be similar to the
} exception which has occurred.
Example, ArithmeticException class.
try and catch
import java.util.*;
class DivideAndSum
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
System.out.println("Enter two int");
int a=kb.nextInt( );
int b=kb.nextInt( );
Example
try
{
int c=a/b;
System.out.println("Division= "+c);
}
catch(ArithmeticException ex)
{
System.out.println(“Please input non zero denominator");
}
int d=a+b;
System.out.println("Sum is="+d);
}
}
Exception Hierarchy
Throwable
Error Exception
Exception
RuntimeException SQLException
ArithmeticException
IOException
FileNotFoundException
NoSuchElementException
InputMismatchException
EOFException
NumberFormatException
MalformedURLException
IndexOutOfBoundsException
SocketException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NullPointerException
NullPointerException
Java’s rule on
multiple catch
Java has a very strict rule while using multiple catch for a
try block.
try try
{ {
---- ----
---- ----
} }
catch(IOException e) catch(FileNotFoundException f)
{ {
---- ----
---- ----
} }
catch(FileNotFoundException f) catch(IOException e)
{ {
---- ----
---- ----
} }
Exercise
catch(ArithmeticException e)
{
System.out.println(“Denominator should not be 0”);
}
catch(InputMismatchException ex)
{
System.out.println(“Please enter integers only”);
System.exit(0);
}
int d=a+b;
System.out.println(“Sum is ”+d);
}
}
End Of Lecture 27