0% found this document useful (0 votes)
7 views48 pages

10_Exception Handling

The document discusses exception handling in Java, defining exceptions as abnormal conditions that arise during runtime and explaining how they can be managed using keywords like try, catch, throw, throws, and finally. It covers the creation and handling of exceptions, the use of multiple catch statements, and the ability to manually throw exceptions. Additionally, it highlights the importance of using finally blocks for cleanup actions and provides examples of built-in exceptions and the creation of custom exceptions.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
7 views48 pages

10_Exception Handling

The document discusses exception handling in Java, defining exceptions as abnormal conditions that arise during runtime and explaining how they can be managed using keywords like try, catch, throw, throws, and finally. It covers the creation and handling of exceptions, the use of multiple catch statements, and the ability to manually throw exceptions. Additionally, it highlights the importance of using finally blocks for cleanup actions and provides examples of built-in exceptions and the creation of custom exceptions.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 48

Module4

Exception
Handling
Chapter 10
• An exception is an abnormal condition that arises in a code
sequence at run time. 2

• In simple words an exception is a run-time error.


• In computer, languages that do not support exception handling,
errors must be checked and handled manually, through the use of
error codes, and so on.
• Java’s exception handling avoids these problems and have run-time
error management.

• For example, exceptions can occur when:


• The file you try to open does not exist.
• The network connection is disrupted.
• Operands being manipulated are out of prescribed ranges.
• The class file you are interested in loading is missing.
Exception Handling Fundamentals
3
• A Java exception is an object that describes an exceptional 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.
4

• Program statements that we want to monitor for exceptions are


contained within a try block
• If an exception occurs within the try block, it is thrown. Our 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 before a method
returns is put in a finally block.
This is the general form of an exception-handling block:
5

try{
// block of code to monitor for errors
}
catch (ExceptionTypel exOb) {
// exception handler for ExceptionTypel
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally{
// block of code to be executed before try block ends
}
Exception Types
6
• All exception types are subclasses of the built-in class Throwable.
Throwable
Exceptional conditions that
user programs should
catch
Exception Error
Automatically defined for
the programs that a user
write, for divison by zero,
invalid array indexing….. 1. These are not
expected to caught under
RuntimeException noraml conditions
2. Used by Java run-time
Systems.
3. Stack overflow is an
Example.
Uncaught Exceptions
7
• Before you learn how to handle exceptions in your program, it is
useful to see what happens when you don’t handle them. This
small program includes an expression that intentionally causes a
divide-by-zero error

class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 /d ;
System.out.println(“a=”+a);
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
} at Exc0.main(Exc0.java:6)
8
• 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, we haven’t supplied any exception handlers of
our own, so the exception is caught by the default handler
provided by the Java run-time system
Using try and catch
9
• Although the default exception handler provided by Java run-time
system is useful for debugging, we usually want to handle an
exception ourselves.
• Doing so provides two benefits.
• First, it allows us to fix errors.
• Second, it prevents the program from automatically terminating.
• At the core of exception handling are try and catch. These
keywords work together; you can’t have a try without a catch, or a
catch without a try.
10
class Exc2 {
public static void main(String args[]) { 11
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.");
}
}
Division by zero.
After catch statement.
Contd…
Notice that 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 (except
in the case of nested try statements, described shortly).
 The statements that are protected by try must be surrounded by curly braces. (That is,
they must be within a block.) You cannot use try on a single statement.
 The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened.
 For example, in the next program each iteration of the for loop obtains two random
integers. Those two integers are divided by each other, and the result is used to divide
the value 12345
13
Contd…

// Handle an exception and try


move on. {
import java.util.Random; b = r.nextInt( );
class HandleError { c = r.nextInt( );
public static void main(String a = 12345 / (b/c);
args[ ]) }
{ catch (ArithmeticException e)
int a=0, b=0, c=0; {
Random r = new Random(); System.out.println("Division by
zero.");
for(int i=0; i<32000; i++)
a = 0; // set a to zero and
{
continue
}
System.out.println("a: " + a);
}
}
}
15
Displaying a Description of an
Exception
 Throwable overrides the toString( ) method (defined by Object) so that it
returns a string containing a description of the exception.
 You can display this description in a println( ) statement by simply passing the
exception as an argument. For example, the catch block in the preceding
program can be rewritten like this:
catch (ArithmeticException e)
{

System.out.println("Exception: " + e);


a = 0; // set a to zero

and continue
When this version is substituted in the program, and the program is run, each
}
divide-by zero error displays the following message:
Exception: java.lang.ArithmeticException: / by zero
 While it is of no particular value in this context, the ability to display a
description of an exception is valuable in other circumstances.
Multiple catch Statements
17
• 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.
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) { 18

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) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}java MultiCatch a = O Divide by 0: java. lang.ArithmeticException: / by zero After try /catch
} blocks.
java MultiCatch TestArg a = 1 Array index oob: java.lang.ArraylndexOutOfBoundsException
42 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
19
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.");
}
}
}
Try Blocks Can Be Nested
20

• The try statements can be nested. 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 next try statement’s
catch handlers are inspected for a match.
• This continues until the success.
• If no catch statement matches, then the java run-time system will
handle the exception.
// An example nested try statements.
class NestTry
{ 21

public static void main(String args[])


{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block

if(a==1)
a = a/(a-a); // division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}catch(ArrayIndexOutOfBoundsException e)
{ 22

System.out.println("Array index out-of-bounds: " + e);


}
}catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
throw
23
• The preceding examples have been catching exceptions generated
automatically by the JVM.
• However, it is possible to manually throw an exception by using
the throw statement.
• Its general form is shown here.
throw ThrowableInstance; //throw exceptOb;

• Here, exceptOb must be an object of an exception class derived


from Throwable or a subclass of Throwable.

• There are two ways you can obtain a Throwable object:


 using a parameter into a catch clause, or
 creating one with the new operator.
24

• 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 the 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.
// Manually throw an exception.
class ThrowDemo 25
{
public static void main(String args[])
{
try
{
System.out.println("Before throw.");
throw new ArithmeticException();
}
catch (ArithmeticException exc)
{ // catch the exception
System.out.println("Exception caught.");
}
System.out.println("After try/catch block.");
The output }
from the program is shown here.
} throw.
Before
Exception caught.
After try/catch block.
// Demonstrate throw. new is used to construct an instance
class ThrowDemo { of NullPointerException 26
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
} All of Java’s
} built-in run-time exceptions have at least
public static void main(String args[])two constructors:
{ one with no parameter
and one that takes a string parameter.
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
} The output from the program is shown here.
} Caught inside demoproc.
} Recaught : java.lang.NullPointerException : demo
throws
27

• 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.
• A throws clause lists the types of exceptions that a method might
throw.
• The general form of a method declaration that includes a throws
clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
exception-list is a comma separated list of the exceptions.
// This program contains an error and will not compile.
class ThrowsDemo 28

{
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
{ 29

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);
}
}
} inside throwOne
Caught: java.lang. IllegalAccessException :demo
30
Using finally
31

• Java supports another statement known as finally statement that can


be used to handle an exception that is not caught by any of the
pervious catch statements.
• finally block can be used to handle any exception generated within
a try block.
• It may be added immediately after the try block or after the last
catch block.
•Try need either catch or finally
finally
33
34
class FinallyDemo {
static void procA() {// Through an exception out of the method.
35
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
static void procC() {
try {
36
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}

public static void main(String args[]) {


try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
37
Java’s Built-In Exception
Java’s Built-in-Exceptions
39
………
40
………..
41
Creating Your Own Exception
42
Subclasses
 to create your own exception types to handle situations specific to your
applications.
 define a subclass of Exception (which is, a subclass of Throwable).
 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.
 You may also wish to override one or more of these methods in
exception classes that you create.
Creating Your Own Exception 43
Subclasses
 Exception defines four public constructors.
 Two support chained exceptions, The other two
are
 Exception( ): creates an exception that has no
description
 Exception(String msg); specify a description of
the exception.
45
46
Chained Exceptions 47
• 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 let you handle this, and any other situation in
which layers of exceptions exist.
48
• 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

• The chained exception methods supported by


Throwable are getCause( ) and initCause( ).
• 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

You might also like