KEMBAR78
M4 C2-Exceptions | PDF | Software Development | Object Oriented Programming
0% found this document useful (0 votes)
30 views49 pages

M4 C2-Exceptions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views49 pages

M4 C2-Exceptions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Java™:

The Complete Reference


UNIT – 3 & Chapter - 10

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• Exception handling - Fundamentals, Exception
types, Uncaught exceptions, using try and catch,
multiple catch clauses, nested try statements,
throw, throws and finally, built- in exceptions,
creating own exception sub classes.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Exception-Handling
• An exception is an abnormal condition that arises in a code
sequence at run time. In other words, an exception is a run-
time error.
• 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.
• In Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at
runtime.
• Exception Handling is a mechanism to handle runtime errors
such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Exception-Handling
• Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.
• Program statements that you want to monitor for exceptions
are contained within a try block.
• If an exception occurs within the try block, it is thrown.
• Your code can catch this exception (using catch) and handle
it in some rational manner.
• 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-Handling
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Exception Types
• All exception types are subclasses of the built-in
class Throwable.
• Thus, Throwable is at the top of the exception class
hierarchy.
• The java.lang.Throwable class is the root class of
Java Exception hierarchy which is inherited by two
subclasses:
1. Exception
2. Error

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Exception Types
Exception Types
• There are mainly two
types of exceptions:
1. checked and
2. unchecked.
• Here, an error is
considered as the
unchecked exception.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Exception Types
• Checked Exception
– The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked
exceptions e.g. IOException, SQLException etc.
– Checked exceptions are checked at compile-time.
• Unchecked Exception
– The classes which inherit RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException
etc.
– Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.
• Error
– Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
What happens when you don’t
handle exceptions

class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Error Message:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
• When the Java run-time system detects the attempt
to divide by zero, it constructs a new exception object
and then throws this exception.
• This causes the execution of Exc0 to stop, because
once an exception has been thrown, it must be caught
by an exception handler and dealt with immediately.
• In this example, haven’t supplied any exception
handlers, so the exception is caught by the default
handler provided by the Java run-time system.
• Any exception that is not caught by your program will
ultimately be processed by the default handler.
• The default handler displays a string describing the
exception, prints a stack trace from the point at which
the exception occurred, and terminates the program.
stack trace
• The stack trace will always show the sequence of method
invocations that led up to the error.
• The stack trace contains all invocations from the start of a thread
until the point it's generated. This is usually a position at which
an exception takes place. For example:
class Exc1 {
The resulting stack trace from the default
static void subroutine() { exception handler:
int d = 0; java.lang.ArithmeticException: / by zero
int a = 10 / d; at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
Using try and catch
• Handle an exception
– First, it allows you to fix the error.
– Second, it prevents the program from automatically
terminating.
• To guard against and handle a run-time error,
simply enclose the code that you want to monitor
inside a try block.
• Immediately following the try block, include a
catch clause that specifies the exception type that
you wish to catch.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
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) {
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
} OUTPUT:
Division by zero.
After catch statement.
The call to println( ) inside the try block is never executed.
Once an exception is thrown, program control transfers out
of the try block into the catch block.
Put differently, catch is not “called,” so execution never
“returns” to the try block from a catch.
Thus, the line “This will not be printed.” is not displayed.
Once the catch statement has executed, program control
continues with the next line in the program following the
entire try/catch mechanism.
• A try and its catch statement form a unit.
• The scope of the catch clause is restricted to those
statements specified by the immediately
preceding try statement.
• A catch statement cannot catch an exception
thrown by another try statement
• The statements that are protected by try must be
surrounded by curly braces.
• You cannot use try on a single statement.
• Throwable overrides the toString( ) method
(defined by Object).
// Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}}
Multiple catch Clauses
• 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
two or more catch clauses, each catching a
different type of exception.
• When an exception is thrown, each catch
statement is inspected in order, and the first one
whose type matches that of the exception is
executed.
• After one catch statement executes, the others are
bypassed, and execution continues after the
try/catch block.
OUTPUT:
// Demonstrate multiple catch statements. C:\>java MultiCatch
class MultiCatch { a=0
Divide by 0:
public static void main(String args[]) { java.lang.ArithmeticException: / by
try { zero
int a = args.length; After try/catch blocks.
C:\>java MultiCatch TestArg
System.out.println("a = " + a); a=1
int b = 42 / a; Array index oob:
int c[] = { 1 }; java.lang.ArrayIndexOutOfBounds
Exception:42
c[42] = 99; After try/catch blocks.
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
/* 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 SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
} Error
} second catch statement is unreachable.
ArithmeticException is a subclass of Exception, the first catch statement
will handle all Exception-based errors, including ArithmeticException.
To fix the problem, reverse the order of the catch statements.
Nested try Statements
• The try statement can be nested. That is, a try
statement can be inside the block of another try.
• Each time a try statement is entered, the context of
that exception is pushed on the stack.
• If an inner try statement does not have a catch
handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers
are inspected for a match.
• This continues until one of the catch statements
succeeds, or until all of the nested try statements are
exhausted.
• If no catch statement matches, then the Java run-time
system will handle the exception.
// An example of nested try statements. Execution of the program with one
class NestTry { command-line argument generates a
public static void main(String args[]) { divide-by-zero exception from within
try { the nested try block. Since the inner
int a = args.length; block does not catch this exception, it is
/* If no command-line args are present */ passed on to the outer try block, where
int b = 42 / a; it is handled.
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used */
if(a==1)
a = a/(a-a); // division by zero
/* If two command-line args are used */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}}
OUTPUT:

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
throw
• catching exceptions that are thrown automatically by
the Java run-time system.
• However, it is possible to throw an exception
explicitly, using the throw statement.
throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type
Throwable or a subclass of Throwable. Primitive types
(int or char), as well as non-Throwable classes, such as
String and Object, cannot be used as exceptions.
• There are two ways you can obtain a Throwable
object:
– using a parameter in a catch clause, or
– creating one with the new operator.
throw
• The flow of execution stops immediately after the
throw statement; any subsequent statements are
not 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 not, 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.
// Demonstrate throw.
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);
}
}
}
This program gets two chances to deal with the same
error.
First, main( ) sets up an exception context and then calls
demoproc( ).
The demoproc( ) method then sets up another
exceptionhandling context and immediately throws a new
instance of NullPointerException, which is caught on the
next line.
The exception is then rethrown.

output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
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.
• 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.
throws
type method-name(parameter-list) throws exception-list
{
// body of method
}
• Here, exception-list is a comma-separated list of the
exceptions that a method can throw.

public static void main(String args[])throws NullPointerException,


ArithmeticException
{
try{
throw new NullPointerExcption();
System.out.println(“aaaaaaaa”); //unreachable code
}
catch(ArithmeticException a){ }
}
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
// This is now correct.
}
class ThrowsDemo {
}
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
finally
• When exceptions are thrown, execution in a method
takes a rather abrupt, nonlinear path that alters the
normal flow through the method.
• Depending upon how the method is coded, it is even
possible for an exception to cause the method to
return prematurely.
• This could be a problem in some methods.
• For example, if a method opens a file upon entry and
closes it upon exit, then you will not want the code
that closes the file to be bypassed by the exception-
handling mechanism.
• The finally keyword is designed to address this
contingency.
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.
• 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.
• This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the beginning
of a method with the intent of disposing of them before
returning.
• The finally clause is optional.
• However, each try statement requires at least one catch or a
finally clause.
// Demonstrate finally. // Execute a try block normally.
class FinallyDemo { static void procC() {
// Through an exception out of the method. try {
static void procA() { System.out.println("inside procC");
try { } finally {
System.out.println("inside procA"); System.out.println("procC's finally");
throw new RuntimeException("demo"); }
} finally { }
System.out.println("procA's finally"); public static void main(String args[]) {
} try {
} procA();
// Return from within a try block. } catch (Exception e) {
static void procB() { System.out.println("Exception caught");
try { }
System.out.println("inside procB"); procB();
return; procC();
} finally { }
System.out.println("procB's finally"); }
}
} inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Java’s Built-in Exceptions
• Inside the standard package java.lang, Java defines
several exception classes.
• The unchecked exceptions defined in java.lang

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Creating Own Exception Subclasses
User defined Exceptions
• Java’s built-in exceptions handle most common errors.
• To create own exception.
• This is: just define a subclass of Exception (subclass of
Throwable).
• Subclasses don’t need to actually implement anything—it is
their existence in the type system that allows you to use
them as exceptions.
• The Exception class does not define any methods of its own.
It does, of course, inherit those methods provided by
Throwable.
• Thus, all exceptions, including those that you create, have
the methods defined by Throwable available to them.
• Exception defines four constructors.
• Two were added by JDK 1.4 to support
chained exceptions.
• The other two are shown here:
1. Exception( )
2. Exception(String msg)
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) { OUTPUT
detail = a; Called compute(1)
} Normal exit
public String toString() { Called compute(20)
return "MyException[" + detail + "]"; Caught MyException[20]
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {System.out.println("Caught " + e);}
}
}
// Example-2 A Class that represents use-defined expception
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException


OUTPUT
public class Main Caught
{ User defined exception…
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException(“User defined exception…");
}
catch (MyException ex)
{
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}
}
Chained Exceptions
• Beginning with JDK 1.4, a new feature has been incorporated into
the exception subsystem: 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.

Although the method must certainly throw an


ArithmeticException, since that is the error that occurred, you
might also want to let the calling code know that the underlying
cause was an I/O error. Chained exceptions handle this, and any
other situation in which layers of exceptions exist.
• 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)
• In the first form, causeExc is the exception that causes
the current exception. That is, causeExc is the
underlying reason that an exception occurred.
• The second form allows you to specify a description at
the same time that you specify a cause exception.
• These two constructors have also been added to the
Error, Exception, and RuntimeException classes.
• The chained exception methods added to Throwable are
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.
• The initCause( ) method associates causeExc with the invoking exception and
returns a reference to the exception. Thus, you can associate a cause with an
exception after the exception has been created.
• However, the cause exception can be set only once. Thus, you can call initCause( )
only once for each exception object.
• Furthermore, if the cause exception was set by a constructor, then you can’t set it
again using initCause( ).
• In general, initCause( ) is used to set a cause for legacy exception classes that
don’t support the two additional constructors described earlier.
// Example – 1 Demonstrate exception chaining.
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());
}
}
} OUTPUT
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( ).
Chained exceptions can be carried on to whatever
depth is necessary. Thus, the cause exception can, itself,
have a cause. Be aware that overly long chains of exceptions
may indicate poor design.
// Example -2 Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
// Creating an exception
NumberFormatException ex = new NumberFormatException("Exception");

// Setting a cause of the exception


ex.initCause(new NullPointerException( "This is actual cause of the exception"));

// Throwing an exception with cause.


throw ex;
}
catch(NumberFormatException ex)
{
// displaying the exception
System.out.println(ex);

// Getting the actual cause of the exception


System.out.println(ex.getCause());
}
} Output:
} java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

You might also like