0% found this document useful (0 votes)
5 views30 pages

Java Exception Handling Basics

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)
5 views30 pages

Java Exception Handling Basics

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

Lecture 13

Exception Handling
Exception Handling-Fundamentals
✔An exception is an abnormal condition that arises in a
code sequence at run time
✔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
✔An exception can be caught to handle it or pass it on
✔Exceptions can be generated by the Java run-time
system, or they can be manually generated by your code

2
Exception Handling
✔Performing action in response to exception
✔Examples
✔Exit program (abort)
✔Deal with exception and continue
✔Print error message
✔Request new data
✔Retry action

3
Representing Exceptions

4
Representing Exceptions
✔Java Exception class hierarchy
ClassNotFoundException

CloneNotSupportedException
Exception
IOException
ArithmeticException
AWTException
NullPointerException
RuntimeException
Object Throwable IndexOutOfBoundsException

NoSuchElementException
LinkageError

VirtualMachineErro
Error r
AWTError
Checked

Unchecked
5
Exception Handling in Java
✔Java exception handling is managed by via five
keywords: try, catch, throw, throws, and
finally
✔Program statements to monitor are contained
within a try block
✔If an exception occurs within the try block, it
is thrown
✔Code within catch block catch the exception
and handle it
6
Example

Output:
Division by zero.
After catch statement.
7
try and catch statement
✔The scope of a 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 the try must be
surrounded by curly braces.

8
Multiple Catch Clauses
✔If more than one can occur, then we use
multiple catch clauses
✔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

9
Example

10
Caution
✔Exception subclass must come before any of of their
superclasses
✔A catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses. So,
the subclass would never be reached if it come after
its superclass
✔For example, ArithmeticException is a subclass of
Exception
✔Moreover, unreachable code in Java generates error

11
Example

12
Nested try Statements
✔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, then the next try statement’s catch
handlers are inspected for a match
✔If a method call within a try block has try
block within it, then then it is still nested try
13
Example

14
throw
✔It is possible for your program to to
throw an exception explicitly
throw ThrowableInstance
✔Here, ThrowableInstance must be an object
of type Throwable or a subclass Throwable
✔There are two ways to obtain a Throwable
objects:
✔Using a parameter into a catch clause
✔Creating one with the new operator

15
Example -throw Statements

Output:
Caught inside demoproc.
Recaught: [Link]: demo
16
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
✔ type method-name parameter-list) throws exception-list
{
// body of method
}
✔ It is not applicable for Error or RuntimeException, or any
of their subclasses

17
Example: incorrect program

18
Example: corrected version

Output:
Inside throwOne.
Caught [Link]: demo
19
Finally Statement
✔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.
✔finally block will be executed whether or not an
exception is thrown.
✔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.
✔Each try clause requires at least one catch or finally
clause.
20
Example

21
Output

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally

22
Uncaught Exceptions
class exc0{ ✔A new exception object is
public static void main(String args[]) constructed and then thrown.
{
int d=0; ✔This exception is caught by the
int a=42/d; default handler provided by the
java runtime system.
}
}
✔The default handler displays a
string describing the exception,
prints the stack trace from the
point at which the exception
occurred and terminates the
Output:
program.
[Link]: / by zero
at [Link]([Link])

23
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.
✔Example:
catch(ArithmeticException e)
{
[Link](“Exception: “+e);
}
✔Output:
Exception: [Link]: / by zero
24
User Defined Exception
✔Define a subclass of the Exception class.
✔The new subclass inherits all the methods of Exception and
can override them.

class MyException extends Exception{


private int a;
MyException(int i) { a = i;}
public String toString (){ return “MyException[“ + a+”]”;}
}

25
Continuation of the Example
class test{
static void compute (int a) throws Myexception{
if(a>10) throw new MyException(a);
[Link](“Normal Exit”);
}
public static void main(String args[]){
try{
compute(1);
compute(20);
}catch(MyException e){ [Link](“Caught “ +e);
}
}

26
Example-2
class InvalidRadiusException extends Exception {
private double r;
public InvalidRadiusException(double radius){
r = radius;
}
public void printError(){
[Link]("Radius [" + r + "] is not valid");
}
}

27
Continuation of Example-2
class Circle {
double x, y, r;

public Circle (double centreX, double centreY, double radius ) throws


InvalidRadiusException {
if (r <= 0 ) {
throw new InvalidRadiusException(radius);
}
else {
x = centreX ; y = centreY; r = radius;
}
}
}

28
Continuation of Example-2
class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(10, 10, -1);
[Link]("Circle created");
}
catch(InvalidRadiusException e)
{
[Link]();
}
}
}
29
Chapter 10 of the text book

30

You might also like