0% found this document useful (0 votes)
66 views

Exception Handling: Another Feature Provided by Java

This document discusses exception handling in Java. It defines exceptions as abnormal runtime errors, such as dividing by zero. When an exception occurs, an exception object is created and thrown. Exception handling allows programs to continue running by catching exceptions and handling them appropriately. The key aspects of exception handling in Java are try/catch blocks to monitor for exceptions, catch blocks to handle specific exception types, and finally blocks to clean up resources. Multiple catch blocks can handle different exception types in order of subclass to superclass. Nested try blocks allow handling exceptions at different levels.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Exception Handling: Another Feature Provided by Java

This document discusses exception handling in Java. It defines exceptions as abnormal runtime errors, such as dividing by zero. When an exception occurs, an exception object is created and thrown. Exception handling allows programs to continue running by catching exceptions and handling them appropriately. The key aspects of exception handling in Java are try/catch blocks to monitor for exceptions, catch blocks to handle specific exception types, and finally blocks to clean up resources. Multiple catch blocks can handle different exception types in order of subclass to superclass. Nested try blocks allow handling exceptions at different levels.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

Exception handling

 Another feature provided by Java

1
Errors:
Compile time error Run time error
All syntax errors will be Some time a program is
detected and displayed compiled successfully but
by the Java Compiler. it will not run properly
.Class file is not created .Class file is created
Eg: missing Eg: divide by zero,
semicolon,missing accessing an element i.e.
brackets, use of out of bounds of array or
undeclared variables, etc a string, etc
2
What is exception?
 An exception is an abnormal condition that
arises in a code sequence at run time.
 An exception is a run time error.
 When the Java interpreter encounters an run
time error eg: such as dividing an integer by
zero, it creates an exception object & throws
it (i.e. it informs us that a error has occurred)

3
/* Program that intentionally causes
a divide-by-zero error.*/
class ExceptionDemo1
{ public static void main(String args[ ])
{ int i = 0;
int j =500/i;
}
}
/*Output:
Exception in thread "main" java.lang.ArithmeticException:
/ by zero
at ExceptionDemo1.main(ExceptionDemo1.java:4)*/

4
Contd..
 The previous program was syntactically
correct and doesn’t cause any problem
during compilation
 However, while executing it displays an
message and stops executing further
statements.

5
Exception-Handling
 When an exceptional condition arises, an object
representing that exception is created and thrown in
the method that caused the error.
 That method may choose to handle the exception itself,
or pass it on. Either way, at some point, the exception
is caught and processed
 If the exception object is not caught and handled
properly, the interpreter will display an error message
and will terminate the program.
 If we want to program to continue with the exception of
the remaining code, then we should to catch the
exception object thrown by error condition and then
display appropriate message for taking corrective
actions. This is known as exception handling
6
The exception handling mechanism
performs following tasks:

1. Find the problem (Hit the exception)


2. Inform that error has occurred (throw the
exception)
3. Receive the error information (Catch the
exception)
4. Take the corrective actions (handle the
exception)

7
Java exception handling is managed via
five keywords:
try, catch, finally, throw, and throws,
Keyword meaning
try Program statements that you want to monitor for
exceptions are contained within try block
If an exception occurs within its try block, it is thrown
catch Your code can catch the exception thrown by try block
(using catch) and handle it some rational manner
finally Any code that absolutely must be executed before a
method returns is put in finally block.
throw The system generated exceptions are automatically thrown
by Java runtime system.
To manually throw an exception use keyword throw.
throws Any exception i.e. thrown out of method must be specified
as such by a throws clause. 8
This is the general form of an exception-handling block:

try { Exception obj creator


// block of code to monitor for errors Try block
}
Statements
that cause an
catch (ExceptionType1 exOb) {
exception
// exception handler for ExceptionType1
}
Throws exception obj

catch (ExceptionType2 exOb) {


// exception handler for ExceptionType2 catch block
} Statements
that handle an
// ... exception
finally {
Exception handler
// block of code to be executed before try block ends 9
}
/* Program that intentionally causes a divide-
by-zero error.*/
class ExceptionDemo1
{ public static void main(String args[ ])
{ int i = 0;
try{
int j =500/i;
System.out.println(" This will not be Executed");
}
//System.out.println("welcome");
catch(ArithmeticException e)
{ // catch divide-by-zero
System.out.println("\n Division by zero....");
System.out.println(" Exception :"+e);
}
System.out.println("\n After catch block....");
}
}
/*Output:
Division by zero....
Exception :java.lang.ArithmeticException: / by zero
10
After catch block....*/
Multiple catch clauses
(Catching multiple exception)
 In some cases more than one exception could be
raised by a single piece of code.
 To handle this type of situation, you can specify more
than one catch clauses, each catching has different
exception
 When exception is thrown , each catch statement is
inspected in order & the first one whose type
matches that of the exception is executed.
 After one catch statement executes, the other are
bypassed & execution continues after try/catch block.

11
/* Program to demonstrates multiple catch clauses */

class ExceptionDemo3
{
public static void main(String args[ ])
{ /*Output:
int arr[] = {5,20,25}; Array index Error.....java.lang.ArrayIndexOutOfBoundsException: 4
After try/catch block....*/
int a = 5;
try { int b = arr[4]/a-arr[0];
}
catch(ArithmeticException e) {
System.out.println("\n Division by zero....."+e); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("\n Array index Error....."+e); }
catch(ArrayStoreException e) {
System.out.println("\n Wrong Data Type....."+e); }

System.out.println("\n After try/catch block...."); } }


12
Output explanation
 Array element arr[4] does not exist because array
‘arr’ is defined to have only three elements arr[0],
arr[1], arr[2]. Therefore index 4 is outside the array
boundary thus block will be executed is
catch(ArrayIndexOutOfBoundsException e)
To catch and handle the error
 Remaining catch blocks are skipped

13
Multiple catch contd
 When you use multiple catch statements, it is
important to remember that exception subclasses
must come before any of their super class.
 Thus a subclass would never be reached if it came
after its super class.
 In Java unreachable code is an error.
 In the next program:
1. Since Arithmetic Exception is a subclass of Exception,
The first catch statement will handle all exception based
errors, including arithmetic exception.
2. This means the second catch statement never execute.
3. To fix the problem reverse the order of the catch.

14
/* This program contains an Error.
A subclass must come before its superclass in a series of catch
statements. if not, unreachable code will be created and a
compile- time error will result */
class ExceptionDemo4
{ public static void main(String args[ ])
{ int x,y,z;
x = 15; y = 15;
try
{ // monitor a block of code.
z = 500/(x-y); // Exception here
}
catch(Exception e)
{
System.out.println("\n Generic Exception catch...."); }
/* This catch never reached because ArithmeticException
is a subclass of Exception */
catch(ArithmeticException e)
{ // Error- unreachable
System.out.println("This is never reached....");
}
}
}

/*Output:
ExceptionDemo4.java 15
Exception java.lang.ArithmeticException has already been caught*/
Nested try statement
 The try statement can be used inside the
block of another try
 If an inner try statement does not have catch
handler for a particular exception, the stack is
unwound and the next try statements catch
handlers are inspected for a match.
 This continues till one of the catch statement
matches, then the Java run time system will
handle the exception.
16
/* Program to demonstrates Nested try statements */
class ExceptionDemo5
{ public static void main(String args[ ])
{ try { int x = args.length;
System.out.println("Number of Command line arguments : "+x);
/* if no command line arguments are present,
the following statment will generate a divide-by-zero exception */

int y = 500/x;
try { // nested try block
/* if one command line argument is used, then a divide-by-zero exception will be generated by the following code.
*/
if (x==1) x = x/(x-x); // division by zero
/* if two command line arguments are used, then generate an out-of-bound exception */
if(x==2)
{
int arr[]={5,20,25};
arr[20]= 100; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("\n Array index out of Bounds...."+e); }
}
catch(ArithmeticException e)
{
System.out.println("\n Division by zero....."+e);
}
}}

17
Output:

O/p1:
C:\>java ExceptionDemo5
Number of Command line arguments : 0

Division by zero.....java.lang.ArithmeticException: / by zero */

O/p2:
C:\>java ExceptionDemo5 nested

Number of Command line arguments : 1

Division by zero.....java.lang.ArithmeticException: / by zero */

O/p3:
C:\>java ExceptionDemo5 nested try
Number of Command line arguments : 2

Array index out of bounds....java.lang.ArrrayIndexOutOfBounds Exception: / by zero */

18
Throwing Exceptions
 It is possible for your program to throw exception explicitly,
using throw statement.
 Here ThrowableInstance must be an object of type
Throwable class itself or a subclass of Throwable.
 There are two ways to obtain a Throwable object:
1. Either creating a Throwable object
throw ThrowableInstance;

2. Creating an object using new operator.


throw new Throwable subclass();
 The flow of execution stops immediately after throw
statement is executed.
 The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception.
 If it does find a match, control is transferred to that
statement
 If it does not found match then the next enclosing try
statement is inspected, and so on.
 If no matching catch is found, then the default exception
handler halts the program and prints the stack trace. 19
/*Program that creates and throws an exception.
The handler that rethrows it to outer handler*/
/* Program to Demonstrates 'throw' */
class ExceptionDemo6
{ static void procedure()
{ try {
throw new NullPointerException("throwDemo");
}
catch(NullPointerException e)
{
System.out.println(" Caught Exception inside 'procedure'.....");
throw e; // rethrow the exception
}
}
public static void main(String args[ ])
{ try
{
/*Output:
procedure(); Caught Exception inside 'procedure'.....
} Recaught Exception.....java.lang.NullPointerException: throwDemo */

catch(NullPointerException e)
{
System.out.println(" Recaught Exception....."+e);
}
}
20
}
Description of program
 This program gets two chances to deal same error .
 First main() sets up an exception context then calls
procedure().
 The procedure() method then sets up another
exception handling context and immediately throws
a new instance of Nullpointer exception, which is
caught in the next line.
 The exception is rethrow.
 All Java’s built-in runtime exception have two types
of constructors:
1. One with no parameter.
2. One with that takes the string parameter

21
The throws statement
 If a method is capable of causing the exception that it
does not handle, it must specify this behavior so that
callers of the method can guard themselves against that
exception.
 You do this by including a throws clause in the method’s
declaration.
 A throws clause lists the types of exceptions that a
method might throw
 This is necessary for all exceptions, except those of
type Error or RuntimeException, or any of their
subclasses.
 All other exceptions that a method can throw must be
declared in the throws clause.
 If they are not, a compile-time error will result.

22
Throws contd..
 General form:
type method-name (parameter-list) throws exception-list
{
// body of method
}

23
Throws contd..
/* Program to Demonstrates 'throws' */

class ExceptionDemo7
{
static void procedure() throws IllegalAccessException
{

System.out.println(" Inside 'procedure( )'.....");


throw new IllegalAccessException("throwsDemo");

}
public static void main(String args[ ])
{ try
{
procedure();
}
catch(IllegalAccessException e)
{ System.out.println(" Caught Exception...."+e);
}
}
}
/*Output:
Inside 'procedure( )'.....
Caught Exception....java.lang.IllegalAccessException: throwsDemo 24
*/
Finally
 finally creates a block of code that will be executed
after a try/catch block has completed and before the
code following the try/catch block.
 The finally block will execute whether or not an
exception is thrown.
 If an exception is thrown, the finallyblock will
execute even if no catch statement matches the
exception.
 Any time a method is about to return to the caller
from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally
clause is also executed just before the method
returns.

25
/* Program to Demonstrates 'finally' */
class ExceptionDemo8
{ // Through an exception out of the method
static void procedure1()
{ try
{
System.out.println(" Inside 'procedure1( )'.....");
throw new ArithmeticException("finallyDemo");
}
finally {
System.out.println(" finally block of 'procedure1( )'.....");
}
}
// Return from within a try block
static void procedure2()
{ try
{
System.out.println("\n Inside 'procedure2( )'.....");
return;
}
finally {
System.out.println(" finally block of 'procedure2( )'.....");
} }
// Execute a try block normally
static void procedure3()
{ try{
System.out.println("\n Inside 'procedure3( )'.....");
}
finally
{ System.out.println(" finally block of 'procedure3( )'.....");
}
26
}
// Execute a try/catch block normally
static void procedure4()
{
try
{
System.out.println("\n Inside 'procedure4( )'.....");
throw new ArithmeticException("finallyDemo");
}
catch(ArithmeticException e)
{
System.out.println(" Caught Arithmetic Exception....");
}
finally
{
System.out.println(" finally block of 'procedure4( )'.....");
}
}
public static void main(String args[ ])
{
try
{
procedure1();
}
catch(Exception e) /*Output:
{ Inside 'procedure1( )'.....
System.out.println(" Caught Exception...."); Caught Exception....
}
procedure2(); finally block of 'procedure1( )'.....
procedure3(); Inside 'procedure2( )'.....
procedure4(); finally block of 'procedure2( )'.....
System.out.println("\n End of the program....."); Inside 'procedure3( )'.....
}}
finally block of 'procedure3( )'.....
Inside 'procedure4( )'.....
Caught Arithmetic Exception....
finally block of 'procedure4( )'.....
End of the program.....*/ 27
Creating your own exceptions
Throwable Exception Your own
Exception

 All the exception that you create have


the methods defined by Throwable
available to them.

28
/* Program to Demonstrates 'Own exception' */
class OwnException extends Exception
{ private int no;
OwnException(int no1)
{ no=no1; }
public String toString()
{ return "OwnException Odd Number("+no+")"; }
}
class ExceptionDemo9
{ static void evenodd(int number) throws OwnException
{ System.out.println("\ncalled evenodd ("+number+")");
if(number%2==0)
System.out.println("Normal Exit....Number is Even ");
else
throw new OwnException(number); }
} public static void main(String args[ ])
{ try{ evenodd(20);
evenodd(25); }
catch(OwnException e)
{ System.out.println("Caught ...."+e); }
} }

29
Contd…
/*Output:
called evenodd (20)
Normal Exit....Number is Even
called evenodd (25)
Caught ....OwnException Odd
Number(25)*/

30
Types of exception
Checked Exception Unchecked Exceptions:
Checked Exceptions extends from These are Runtime Exceptions and
Exception class. extends RunTimeException class.
The compiler forces us to handle these There is no need to handle these
exception either by try-catch or using exceptions as they can't be predicted.
throws clause. These occur due to logical errors in
the program.
The compiler forces us to handle these The compiler will not enforce us to
exception either by try-catch or using handle these exceptions.
throws clause.
Examples: SQLException, Examples:
IOException,Interrupted Exception. DivideByZero,NullpointerException

31
Thrwable --
Error and Exception

32
33

You might also like