Module4opp Part3
Module4opp Part3
Exception-Handling Fundamentals
• A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
• 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.
• Exceptions can be generated by the Java run-time system,
• or they can be manually generated by your code.
• Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
• Briefly, here is how they work. Program statements that create exceptions are contained
within a try block.
• If an exception occurs within the try block, it is thrown.we can catch this exception
(using catch) and handle it .
• System-generated exceptions are automatically thrown by the Java run-time system.
• To manually throw an exception, 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 absolutely must be executed after a try block completes is put in a finally
block.
Exception Types
• All exception types are subclasses of the built-in class Throwable. Thus, Throwable is
at the top of the exception class hierarchy.
• Immediately below Throwable are two subclasses that partition exceptions into two
distinct branches.
• One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch.
• There is an important subclass of Exception, called RuntimeException. Exceptions of
this type are automatically defined for the programs that you write and include things
such as division by zero and invalid array indexing.
• The other branch is topped by Error, which defines exceptions that are not expected to
be caught under normal circumstances by your program.
• Exceptions of type Error are used by the Java run-time system to indicate errors having
to do with the run-time environment, itself. Stack overflow is an example of such an error
Uncaught Exceptions
Page 2
Using try and catch
• Although the default exception handler provided by the Java run-time system is useful for
debugging,we should handle an exception ourself.
• Doing so provides two benefits.
• First, it allows you to fix the error.
• Second, it prevents the program from automatically terminating.
• To handle a run-time error, simply enclose the code inside a try block.
• Immediately following the try block, include a catch clause that specifies the exception
type to catch
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
Page 3
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
Page 4
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
output:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
Page 5
catch(ArithmeticException e)
{
System.out.println("This is never reached.");
}
}
}
• If this program is compiled , we will receive an error message stating that the second
catch statement is unreachable because the exception has already been caught.
• Since ArithmeticException is a subclass of Exception, the first catch statement will
handle all Exception-based errors, including ArithmeticException.
• This means that the second catch statement will never execute. To fix the problem,
reverse the order of the catch statements.
• The try statement can be nested. That is, a try statement can be inside the block of
another try.
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
Page 6
}
catch(Exception e)
{
}
....
Example :
class Excep
{
public static void main(String args[]){
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
Try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{
System.out.println("handeled");
}
Page 7
System.out.println("normal flow..");
}
run:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
handeled
normal flow..
throw
• it is possible for your program to throw an exception explicitly, using the throw
statement.
• The general form of throw is shown here:
throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
• Primitive types, such as int or char, as well as non-Throwable classes, such as String
and Object, cannot be used as exceptions.
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
Page 8
}
}
}
Throws
• If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
• We can 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 the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
Page 9
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
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 finally block will execute even if no catch statement
matches the exception
class FinallyDemo
{
static void procA()
{
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
Finally
{
System.out.println("procA's finally");
}
}
Page 10
}
Finally System.out.println("inside procC");
{
}
} System.out.println("procC's finally");
{
try
{
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}
}
• Here is the output generated by the preceding program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Page 11
Java’s Built-in Exceptions
• Inside the standard package java.lang, Java defines several exception classes.
• The most general of these exceptions are subclasses of the standard type
RuntimeException
• if the method can generate one of these exceptions and does not handle it itself. These are
called checked exceptions.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on
an unlocked thread.
IllegalStateException Environment or application is in incorrect
state.
NullPointerException Invalid use of a null reference.
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a
completed stack trace
Throwable getCause( ) Returns the exception that underlies the current
exception. If there is no underlying exception, null
is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace, one
element at a time, as an array of
Chained Exceptions
• The chained exception feature allows you to associate another exception with an
exception.
• This second exception describes the cause of the first exception.
• For example, imagine a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero.
• However, the actual cause of the problem was that an I/O error occurred, which caused
the divisor to be set improperly.
• To allow chained exceptions, two constructors and two methods were added to
Throwable.
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
• These two constructors have also been added to the Error, Exception, and
RuntimeException classes.
• The chained exception methods added to Throwable are getCause( ) and initCause( ).
• These methods are shown
Throwable getCause( )
Throwable initCause(Throwable causeExc)
• The getCause( ) method returns the exception that underlies the current exception. If
there is no underlying exception, null is returned.
Page 13
• The initCause( ) method associates causeExc with the invoking exception and returns a
reference to the exception.
class ChainExcDemo
{
static void demoproc()
{
// create an exception
NullPointerException e =
new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}
The output from the program is shown here:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
• In this example, the top-level exception is NullPointerException.
• To it is added a cause exception, ArithmeticException. When the exception is thrown
out of demoproc( ), it is caught by main( ).
• There, the top-level exception is displayed, followed by the underlying exception, which
is obtained by calling getCause( ).
******************************************************************************
uncaught Exception
public class Exec0
{
Page 14
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
Page 15
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Nested try
public class NestedTry
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5]; a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Page 16
throw example1 :
import java.util.Scanner;
if(d<0 ||d>31)
{
throw new IllegalArgumentException("invalid date");
}
}
catch(IllegalArgumentException e)
{
System.out.println("reason "+e);
}
}
}
Page 17
throwexample 2 :
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc."+e);
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}
throw example 3:
class Throw2
{
void checkAge (int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
Page 18
System.out.println("End Of Program");
}
}
throws example 1:
class Throws1
{
public static void main(String args[])
{
try
{
process( );
}
catch(IllegalAccessException e)
{
System.out.println("caught : "+e);
}
}
}
Throws example 2:
import java.io.*;
class Throws2
{
static void m1() throws IOException
{
throw new IOException("device error");//checked exception
}
Page 19
{
try
{
m2();
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
m1();
}
catch(IOException e)
{
System.out.println(e);
}
System.out.println("normal flow...");
}
}
Page 20
finally
{
System.out.println("procB's finally");
}
}
class UserDefinedException
{
Page 21
public static void main(String args[])
{
try
{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
class UserDefinedException1
{
static void productCheck(int weight) throws InvalidProductException
{
if(weight<100)
{
throw new InvalidProductException("Product Invalid");
}
}
Page 22
System.out.println(ex.getMessage());
}
}
}
Chained Exception
class ChainedException
{
public static void main(String[] args)
{
try
{
// Creating an exception
ArithmeticException ex = new ArithmeticException("Exception");
catch(ArithmeticException ex)
{
// displaying the exception
System.out.println(ex);
Page 23