Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Exception-Handling

Java Programming

Session 3 - Exception-Handling 1
TCS Confidential Java 1
Programming
PRELUDE
Exception-handling,
Exception Types ,Uncaught
Exceptions, Exception Clauses
try, catch, throw,throws,finally,
Java’s Built-in Exceptions

Session 3 - Exception-Handling 2
TCS Confidential Java 2
Programming
Exception-Handling
A Java exception is an object
that describes an exceptional
/error condition that has
occurred in a piece of code at
“RUN TIME”

Session 3 - Exception-Handling 3
TCS Confidential Java 3
Programming
Exception
When an exceptional
condition arises, an object
representing that exception is
created and thrown in the
method that caused the error.

Session 3 - Exception-Handling 4
TCS Confidential Java 4
Programming
Diagrammatic Representation of Program
Execution
Java Code classes.zip: classes needed at run-
time by Java Interpreter
Exception Classes
Java Compiler Java Interpreter
javac java
Bytecode
No
Error or Exception Errors

Exception Type determined Program


Execution
Object of Exception Class created

Related message displayed


Session 3 - Exception-Handling 5
TCS Confidential Java 5
Programming
Exceptions can be generated by:
Java run-time system:-
ERROR
Generated by the code:-
EXCEPTION

Session 3 - Exception-Handling 6
TCS Confidential Java 6
Programming
THROWABLE
All Exception types are
subclasses of the built-in
class THROWABLE.

THROWABLE is at the top of


the Exception class
Hierarchy.
Session 3 - Exception-Handling 7
TCS Confidential Java 7
Programming
Exception Types
Throwable

Exception Error
Linkage
Run-time ClassNotFound Error
Exception
Stack overflow
ArrayIndexOutOfBounds
Session 3 - Exception-Handling 8
TCS Confidential Java 8
Programming
Uncaught Exceptions
class UncaughtEx{
public static void main(String args[]) {
int d = 0;
int a = 42/d;
}}
Output :
java.lang.ArithmeticException:/by zero
at Exc0.main(UncaughtEx.java:4)
Session 3 - Exception-Handling 9
TCS Confidential Java 9
Programming
Five keywords
Java exception-handling
try
catch
throw
throws
finally
Session 3 - Exception-Handling 10
TCS Confidential Java 10
Programming
Exception-Handling ...
Program statements to be
monitored for exceptions are
contained within a try block.

Your code can catch this


exception using catch and
handle it in some rational
manner.
Session 3 - Exception-Handling 11
TCS Confidential Java 11
Programming
Use the keyword throw to
throw an exception.

Any exception that is thrown


out of a method throws
clause.

Any code that absolutely


must be executed is put in a
finally block.
Session 3 - Exception-Handling 12
TCS Confidential Java 12
Programming
class HandledException{
public static void main(String args[])
{ int d, a ;
try { d = 0;a = 42 /d; }
catch(ArithmeticException e)
{System.out.println(“Division by 0”);}
} }
Output: Division by 0
Session 3 - Exception-Handling 13
TCS Confidential Java 13
Programming
Using try and catch
Advantages of handling
exceptions:
It allows the programmer to
fix the error
Prevents the program from
automatically terminating

Session 3 - Exception-Handling 14
TCS Confidential Java 14
Programming
try-catch Control Flow

code before try


exception occurs
try block catch block

code after try


Session 3 - Exception-Handling 15
TCS Confidential Java 15
Programming
try-catch Control Flow
code before try
exception occurs
try block catch block
no exceptions occur

code after try


Session 3 - Exception-Handling 16
TCS Confidential Java 16
Programming
Multiple catch clauses
One block of code causes
multiple Exception.
Two or more catch clauses.

Exception subclass must


come before any of their super
classes.
Unreachable code.
Session 3 - Exception-Handling 17
TCS Confidential Java 17
Programming
public static void main(String args[]) {
try { int a = args.length;
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 block”);}

Session 3 - Exception-Handling 18
TCS Confidential Java 18
Programming
Nested try Statements

A try and its catch can be


nested inside the block of
another try.

It executes until one of the


catch statements succeeds or
Java run-time system handle
the exception.
Session 3 - Exception-Handling 19
TCS Confidential Java 19
Programming
try{ int a=args.length;
int b=42/a;
try{int c[ ]={1},c[40]=99;}
catch(ArrayIndexOutOfBoudnds
Exception e)
{System.out.println(e); }
}
catch(ArithmeticExceptione)
{} Session 3 - Exception-Handling 20
TCS Confidential Java 20
Programming
The finally Clause
finally creates a block of
code that will be executed
(whether or not an exception
is thrown)

Session 3 - Exception-Handling 21
TCS Confidential Java 21
Programming
class FinallyDemo {
int [ ] num1= {12, 16, 10, 8, -1, 6};
int [ ] num2 = { 1, 5, 35, 20, 1, 13};
public static void main(String [ ] args) {
FinallyDemo f = new FinallyDemo( );
f.readNums(f.num1);
f.readNums(f.num2);}

Session 3 - Exception-Handling 22
TCS Confidential Java 22
Programming
void readNums(int [ ] array) {
int count = 0, last = 0 ;
try {
while (count < array.length) {
last = array[count++];
if (last == -1) return; }}
finally
{System.out.println(“Last” +
last);}
Session 3 - Exception-Handling 23
TCS Confidential Java 23
Programming
try-catch Control Flow
code before try
exception occurs
try block catch block

finally block (if it exists)


code after try
Session 3 - Exception-Handling 24
TCS Confidential Java 24
Programming
The throw clause
Throw an exception explicitly.
throw ThrowableInstance

Throwable object:
Using a parameter into a catch
clause
Creating one with the new
operator.
Session 3 - Exception-Handling 25
TCS Confidential Java 25
Programming
class ThrowDemo {
static void demoproc( ){
try { throw new
NullpointerException(“demo”);}
catch(NullPointerException e) {
System.out.println(“demoproc.”);
throw e;} }
// Output: demoproc
Session 3 - Exception-Handling 26
TCS Confidential Java 26
Programming
Continued…
public static void main(Stringargs[])
{try { demoproc();}
catch(NullPointerException e)
{System.out.println(“Recaught”+e);}
}}
//Recaught:java.lang.NullPointerEx
ception: demo
Session 3 - Exception-Handling 27
TCS Confidential Java 27
Programming
Example

Session 3 - Exception-Handling 28
TCS Confidential Java 28
Programming
The throws clause
A throws :-Is used to throw a
Exception that is not handled.

Error and RuntimeException


or any of their subclasses
don’t use throws.

Session 3 - Exception-Handling 29
TCS Confidential Java 29
Programming
The throws clause -continued

Type method-name
(parameter-list) throws
exception-list
{ // body of method }

Session 3 - Exception-Handling 30
TCS Confidential Java 30
Programming
class ThrowsDemo {
static void throwProc( ) throws
IIlegalAccessException {
throw new
IllegalAccessException(“demo”);
}
public static void main (String args[] ) {
try { throwProc( );}
catch(IllegalAccessException e){
System.out.println(“Caught ” + e);}}
}TCS Confidential
Session 3 - Exception-Handling
Java 31
Programming
31
Java’s Built-in Exceptions

Java defines several


exception classes inside the
standard package java.lang
RuntimeException or Error

Session 3 - Exception-Handling 32
TCS Confidential Java 32
Programming
Unchecked Exceptions
Unchecked Exception =
Runtime Exceptions/ERROR
Example:
•NumberFormatException
•IllegalArgumentException
•OutOfMemoryError

Session 3 - Exception-Handling 33
TCS Confidential Java 33
Programming
Checked Exceptions
Checked Exception = checked at
compile time
These errors are due to
external circumstances that
the programmer cannot
prevent
Example:-IOException
Session 3 - Exception-Handling 34
TCS Confidential Java 34
Programming
Java’s Built-in Exceptions ...
The following are Java’s Checked
Exceptions:
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
Session 3 - Exception-Handling 35
TCS Confidential Java 35
Programming
PRELUDE
Garbage collection ,
User defined Exceptions,
Assertions,
chained Exceptions

Session 3 - Exception-Handling 36
TCS Confidential Java 36
Programming
The Utility of Backtracking
Backtracking is the process by
which the stack frame is
unwound in the presence of an
unhandled exception.
Objects created on the stack
are discarded to the GC.
Session 3 - Exception-Handling 37
TCS Confidential Java 37
Programming
Garbage Collection

When no references to an
object exists that object is
assumed to be not needed.
Java’s garbage collector
(GC) offers each method a
type of destructor called
‘finalizer()’.
Session 3 - Exception-Handling 38
TCS Confidential Java 38
Programming
It is called with neither timing
nor order guaranteed
To ensure that the resources
are freed finalize() method.
****System.gc();
protected void finalize()
{ //finalization code}

Session 3 - Exception-Handling 39
TCS Confidential Java 39
Programming
Creating Your Own Exception
Classes

All user-created exceptions –


subclass of Exception
All methods inherited
Throwable.

Session 3 - Exception-Handling 40
TCS Confidential Java 40
Programming
Demo of ExcepDemo.java
class YourException extendsException
{ private int detail;
YourException(int a)
{ detail = a; }
public String toString( )
{return “YourException[“ + detail +”]”; }
}

Session 3 - Exception-Handling 41
TCS Confidential Java 41
Programming
class ExcepDemo {
static void compute(int a)
throwsYourException
{
if( a > 10)
throw newYourException(a);
System.out.println(“Normal Exit”)
}
Session 3 - Exception-Handling 42
TCS Confidential Java 42
Programming
ExcepDemo.java ...
public static void main
(String args[ ]){
try { compute(1); compute(20);}
catch(YourException e)
{System.out.println(“Caught“+e)}
}}
Session 3 - Exception-Handling 43
TCS Confidential Java 43
Programming
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught YourException[20]

Session 3 - Exception-Handling 44
TCS Confidential Java 44
Programming
Assertions
Assertions are conditions
that should be true at a
particular point in a method.

Assertions can be validated


using the assert statement

Session 3 - Exception-Handling 45
TCS Confidential Java 45
Programming
Assertions

assert statement
Evaluates -true or false
assert exp;
AssertionError if exp false
assert exp1 :exp2;
exp2 is error message

Session 3 - Exception-Handling 46
TCS Confidential Java 46
Programming
By default, assertions are
disabled
Assertions can be enabled
with the
–ea command-line option

Session 3 - Exception-Handling 47
TCS Confidential Java 47
Programming
assert
(number>=0&&number<=10):
"bad number"+ number

If you enter a number 50

Exception in thread "main"


java.lang.AssertionError:
bad number:50
Session 3 - Exception-Handling 48
TCS Confidential Java 48
Programming
Chained Exceptions
Associate one exception with
another.
Second exception describes the
cause of the first exception.
initCause(Throwable cauExc)
getCause()
Session 3 - Exception-Handling 49
TCS Confidential Java 49
Programming
static void demo(){
NullPointerException
e=newNullPointerException(“Top”);
e.initCause(newArithmeticException
(“cause”));
throw e;
}
e.getCause();
NullPointerException,Original Cause
ArithmeticException.
Session 3 - Exception-Handling 50
TCS Confidential Java 50
Programming
When to Use Exceptions
Deal with the exception try
and catch.
Pass the exception up the
calling chain by adding throws
clause
Both by catching the using
catch and then explicitly
rethrowing it using throw
Session 3 - Exception-Handling 51
TCS Confidential Java 51
Programming
When Not to Use Exceptions
When exception is something
that is expected and could be
avoided easily with a simple
expression.

Exceptions take up lot of


processing time. A simple test or
series of tests will run much
faster than exception-handling.

Session 3 - Exception-Handling 52
TCS Confidential Java 52
Programming
Java exception system was
designed to warn users for the
possibility of their occurrence.
Ignoring them could have
resulted into fatal errors.

Even worse, adding throws to


your methods to avoid
exceptions means that the users
of your methods will have to
deal with them - method made
more difficult to use.
Session 3 - Exception-Handling 53
TCS Confidential Java 53
Programming
Why Runtime Exceptions are Not
Checked
Many of the operations and
constructs of the Java
language can result in runtime
exceptions. The information
available to a Java compiler
The level of analysis the
compiler performs, are usually
not sufficient to establish that
such runtime exceptions
cannot occur.
Session 3 - Exception-Handling 54
TCS Confidential Java 54
Programming

You might also like