You are on page 1of 40

Exception Handling

Objective ….
 What is an Exception?
 What happens when an Exception occurs?
 Benefits of Exception Handling framework
 Catching exceptions with try-catch
 Catching exceptions with finally
 Throwing exceptions
 Rules in exception handling
 Exception class hierarchy
 Creating your own exception class (throw)
 throws
Exception …
• Exceptional event
• Error that occurs during runtime
• Cause normal program flow to be disrupted
• Examples
– Divide by zero errors
– Accessing the elements of an array beyond its range
– Invalid input
– Hard disk crash
– Opening a non-existent file
– Heap memory exhausted
Exception ….
• When an exception occurs within a method,
the method creates an exception object and
hands it off to the runtime system
– Creating an exception object and handing it to the
runtime system is called “throwing an exception”
– Exception object contains information about the
error, including its type and the state of the
program when the error occurred
Exception handling
• exception handling refers to handling of
abnormal or unexpected events.
• Exception is class and it has sub classes
• The diff sub classes are the according to
exception possible in java.(list)
Exception Type
ArithmeticException divide by zero
ArrayIndexOutOfBoundsExceptiona accessing an element out of the size of
an array i.e outside its boundary

ArrayStoreException incompatible type element to an array


NumberFormatException
StringIndexOutOfBounds similar to array index
out of bounds exception ,but an array
of strings
NullPointerException
Class CastException
• Java exception handling is managed via five keywords: try,
catch, throw, throws and finally.
1) Try & catch :
• The try statement contains the program statements that you
want to monitor for exceptions contained within that block
• The catch statement handles this exception .The System
generated exceptions are automatically thrown by the java
run-time environment.
• To manually throw an exception we should use the keyword
throw .
• Any exception that is thrown out of a method must be
specified as such by a throws clause.
• Any code that must be executed before a method returns is
put in a finally block
By using exceptions to manage errors, Java programs have the
following advantages over traditional error management
techniques:
SYNTAX OF EXCEPTION HANDALING

try BLOCK
Exception
object creator
STATEMENT THAT CAUSES AN
Throws EXCEPION

exception
Object Catch BLOCK

STATEMENT THAT HANDALING THE


EXCEPTION
Using try and catch
To respond to an exception, the call to the method that produces it must be placed
within a try block.Every try block is associated with one or more catch blocks. Here is a
try block:
try
{ // method calls go here
}
If a method is to catch exceptions thrown by the methods it calls , the calls must be
placed within a try block. If an exception is thrown, it is handled in a catch block.
Different catch blocks handle different types of exceptions. This is a try block and a
catch block set up to handle exceptions of type Exception:-
try
{// body of program or method calls go here
}
catch( Exception e )
{
// handle exceptions here
}
//ArithmeticException :generated by the division-by-zero error
class Exc2
{ public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}}
/* This program generates the following output:
Division by zero.
After catch statement
*/
WAP to perform division of two numbers
accepted from user. Handling the divide
by
Zero exception using the try-catch block
import java.util.*;
class Divide{
public static void main(String args[])
{
int a,b,res;
Scanner br =new Scanner (System.in);
System.out.println("Enter two numbers:");
try
{
a=br.nextInt();
b=br.nextInt();
res=a/b;
System.out.println("The Quotient=" + res);
}
catch(ArithmeticException ae)
{System.out.println("Exception has occurred. You have entered the divisor as
zero");
} }}
Multiple try catch Blocks (may 2008)
When multiple exceptions are to be caught,we
must use
multiple try catch block. But we must have all the
statements that can be generate an exception in
one try
block and the catch blocks for all exceptions that
can be
generated.
try
{
// method calls go here
}
catch( SomeExceptionClass e )//catch(exeception_class_name
object _name)
{
// handle SomeExceptionClass exceptions here
}
catch( SomeOtherExceptionClass e ) //catch(exeception_class_name
object _name)
{
// handle SomeOtherExceptionClass exceptions here
}
WAP to perform division of two numbers
accepted from user . Handling the
number
format exception and also handle the
divide
by Zero exception using multiple try-
catch
block .
import java.util.*;
class Divide
{ public static void main(String args[])
{
int a=0,b=0,res;
Scanner br =new Scanner (System.in);
System.out.println("Enter two numbers:");
try
{ a=br.nextInt();
b=br.nextInt();
res=a/b;
System.out.println("The Quotient=" + res); }
catch(ArithmeticException ae)
{System.out.println("Exception has occurred. You have entered the divisor as
zero"); }
catch (NumberFormatException ne)
{ System.out.println("Invalid number");
} }
}
• Nested try catch Block
When multiple exceptions are to be caught there is one
more method called as nested try catch block.
The nested try catch block as the name says ,has a try
catch block inside another try block.
WAP to perform division of two numbers
accepted from user . Handling the
number
format exception and also handle the
divide
by Zero exception using nested try-catch
block .
import java.util.*;
class Divide{ public static void main(String args[])
{ int a=0,b=0,res;
Scanner br =new Scanner (System.in);
System.out.println("Enter two numbers:");
try {
a=br.nextInt( );
b=br.nextInt( );
try
{ res=a/b;
System.out.println("The Quotient=" + res);
}
catch(ArithmeticException ae)
{ System.out.println("Exception has occurred. You have entered the divisor as
zero");
}
}
catch(NumberFormatException ne)
{ System.out.println(“invalid number”);
}
} }
Output
Enter a numbers:
4
0
Execption has occurred .you have entered the divisor as zero

Output
Enter two number
4
a
Invalid number
Finally Block ….

-A finally block is always executed irrespective


of whether the execution occurred or not
-it is an optional block .it is not necessary to
have a finally block .you may just have try
and the catch blocks
Syntax
try
{
//code to be monitored for exceptions>
}
catch (Exception_class_name object_name)
{
//handler if ExceptionType occurs
}
}
finally
{
//code to be executed before the try block ends
}

 Contains the code for cleaning up after a try or a catch


WAP to perform division of two numbers
accepted from user . Handling the
divide by Zero exception using try-
catch-finally block .
import java.util.*; catch(ArithmeticException ae)
class Divide {
{ System.out.println("Exception has
public static void main(String args[]) occurred. You have entered the divisor as
{ zero");
int a,b,res; }
Scanner br=new Scanner(System.in); finally
System.out.println("Enter two {
numbers:"); System.out.println("In Finally Block");
a=br.nextInt(); }
b=br.nextInt(); }
try }
{
res=a/b;
System.out.println("The Quotient=" +
res);
}
Enter two number
4
0
Exception has occurred you have the divide as zero
In finally Block
Enter two numbers
4
2
The Quotient=2
In finally block
Keyword “throw”
->Using the keyword throw you can make your
own conditions to throw the exceptions.
->It will not built-in –type exception .it will be
your own created exception.
Example
You accept an integer from user as the month
number the user enters 25 .this is invalid
month number, but not invalid integer . hence
the number format exception will not take
place according to rules . but you can throw
your own exception for this .
Write a program to accept & display the month number .throw an
number format exception if improper month number is enter
import java.util.*;
class Month
{public static void main(String args[])
{ int m;
Scanner br = new Scanner(System.in);
System.out.println("Enter month number:");
m=br.nextInt();
try { if(m>12 || m<1)
throw new NumberFormatException();
System.out.println("Month number entered is "+m);
}
catch(NumberFormatException ne)
{ System.out.println("Invalid month number"); }}}
// output
Enter month number
15
Invalid month number
//output
Enter month number
3
month number entered is 3
This can also be done by making a new exception
class for example MonthNumberException
Write a program to accept & display a month number
.throw an exception if improper month number is
entered .make your own exception class to handle this
exception
import java.io.*;
class MonthNumberException extends Exception
{
public MonthNumberException(String str)
{
System.out.println(str);
}}
class Month
{
public static void main(String args[]) throws IOException
{
int m;
Scanner br=new Scanner(System.in);
System.out.println("Enter month number:");
m=br.nextInt();
try
{
if(m>12 || m<1)
throw new MonthNumberException("Invalid Month Number");
System.out.println("Month number entered is "+m);
}
catch(MonthNumberException me)
{
}
}
}

You might also like