Professional Documents
Culture Documents
Exception-Handling: Java Programming
Exception-Handling: Java Programming
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
Session 3 - Exception-Handling 6
TCS Confidential Java 6
Programming
THROWABLE
All Exception types are
subclasses of the built-in
class 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.
Session 3 - Exception-Handling 14
TCS Confidential Java 14
Programming
try-catch Control Flow
Session 3 - Exception-Handling 18
TCS Confidential Java 18
Programming
Nested try Statements
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
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.
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
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
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.
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
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.