Unified Modeling Language (UML) - Gujarat Informatics Limited
Exception-Handling Java Programming - Gujarat Informatics Limited
Transcript of Exception-Handling Java Programming - Gujarat Informatics Limited
![Page 1: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/1.jpg)
Session 3 - Exception-Handling Java Programming
11TCS Confidential
Exception-HandlingJava Programming
![Page 2: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/2.jpg)
Session 3 - Exception-Handling Java Programming
22TCS Confidential
PRELUDEException-handling,
Exception Types ,Uncaught Exceptions, Exception Clausestry, catch, throw,throws,finally,
Java’s Built-in Exceptions
![Page 3: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/3.jpg)
Session 3 - Exception-Handling Java Programming
33TCS Confidential
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”
![Page 4: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/4.jpg)
Session 3 - Exception-Handling Java Programming
44TCS Confidential
ExceptionWhen an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.
![Page 5: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/5.jpg)
Session 3 - Exception-Handling Java Programming
55TCS Confidential
Diagrammatic Representation of Program Execution
Java Interpreter java
Program Execution
No ErrorsError or Exception
Exception Type determined
Related message displayed
Object of Exception Class created
Java Code classes.zip: classes needed at run-time by Java Interpreter
Exception Classes
Java Compiler javac Bytecode
![Page 6: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/6.jpg)
Session 3 - Exception-Handling Java Programming
66TCS Confidential
Exceptions can be generated by:Java run-time system:-
ERRORGenerated by the code:-
EXCEPTION
![Page 7: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/7.jpg)
Session 3 - Exception-Handling Java Programming
77TCS Confidential
THROWABLEAll Exception types are
subclasses of the built-inclass THROWABLE.
THROWABLE is at the top of the Exception classHierarchy.
![Page 8: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/8.jpg)
Session 3 - Exception-Handling Java Programming
88TCS Confidential
Exception TypesThrowable
Exception Error
Stack overflowArrayIndexOutOfBounds
Run-time Exception
ClassNotFoundLinkage Error
![Page 9: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/9.jpg)
Session 3 - Exception-Handling Java Programming
99TCS Confidential
Uncaught Exceptionsclass 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)
![Page 10: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/10.jpg)
Session 3 - Exception-Handling Java Programming
1010TCS Confidential
Five keywordsJava exception-handling
trycatchthrowthrows finally
![Page 11: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/11.jpg)
Session 3 - Exception-Handling Java Programming
1111TCS Confidential
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.
![Page 12: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/12.jpg)
Session 3 - Exception-Handling Java Programming
1212TCS Confidential
Use the keyword throw to throw an exception.
Any exception that is thrown out of a method throwsclause.
Any code that absolutelymust be executed is put in a finally block.
![Page 13: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/13.jpg)
Session 3 - Exception-Handling Java Programming
1313TCS Confidential
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
![Page 14: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/14.jpg)
Session 3 - Exception-Handling Java Programming
1414TCS Confidential
Using try and catchAdvantages of handling
exceptions:It allows the programmer to
fix the errorPrevents the program from
automatically terminating
![Page 15: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/15.jpg)
Session 3 - Exception-Handling Java Programming
1515TCS Confidential
try-catch Control Flow
code before try
try block catch blockexception occurs
code after try
![Page 16: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/16.jpg)
Session 3 - Exception-Handling Java Programming
1616TCS Confidential
try-catch Control Flow
code before try
try block
code after try
no exceptions occur
catch blockexception occurs
![Page 17: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/17.jpg)
Session 3 - Exception-Handling Java Programming
1717TCS Confidential
Multiple catch clausesOne block of code causes
multiple Exception.Two or more catch clauses.
Exception subclass must come before any of their super classes.Unreachable code.
![Page 18: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/18.jpg)
Session 3 - Exception-Handling Java Programming
1818TCS Confidential
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”);}
![Page 19: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/19.jpg)
Session 3 - Exception-Handling Java Programming
1919TCS Confidential
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.
![Page 20: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/20.jpg)
Session 3 - Exception-Handling Java Programming
2020TCS Confidential
try{ int a=args.length; int b=42/a;
try{int c[ ]={1},c[40]=99;}catch(ArrayIndexOutOfBoudndsException e){System.out.println(e); }
}catch(ArithmeticExceptione){}
![Page 21: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/21.jpg)
Session 3 - Exception-Handling Java Programming
2121TCS Confidential
The finally Clausefinally creates a block of
code that will be executed (whether or not an exception is thrown)
![Page 22: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/22.jpg)
Session 3 - Exception-Handling Java Programming
2222TCS Confidential
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);}
![Page 23: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/23.jpg)
Session 3 - Exception-Handling Java Programming
2323TCS Confidential
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);}
![Page 24: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/24.jpg)
Session 3 - Exception-Handling Java Programming
2424TCS Confidential
try-catch Control Flow
try blockexception occurs
code after try
code before try
finally block (if it exists)
catch block
![Page 25: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/25.jpg)
Session 3 - Exception-Handling Java Programming
2525TCS Confidential
The throw clauseThrow an exception explicitly.
throw ThrowableInstance
Throwable object:Using a parameter into a catchclause Creating one with the new
operator.
![Page 26: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/26.jpg)
Session 3 - Exception-Handling Java Programming
2626TCS Confidential
class ThrowDemo {static void demoproc( ){try { throw newNullpointerException(“demo”);}catch(NullPointerException e) {
System.out.println(“demoproc.”);throw e;} }
// Output: demoproc
![Page 27: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/27.jpg)
Session 3 - Exception-Handling Java Programming
2727TCS Confidential
Continued…public static void main(Stringargs[]){try { demoproc();}catch(NullPointerException e) {System.out.println(“Recaught”+e);}} }
//Recaught:java.lang.NullPointerException: demo
![Page 28: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/28.jpg)
Session 3 - Exception-Handling Java Programming
2828TCS Confidential
Example
![Page 29: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/29.jpg)
Session 3 - Exception-Handling Java Programming
2929TCS Confidential
The throws clauseA throws :-Is used to throw a
Exception that is not handled.
Error and RuntimeExceptionor any of their subclasses don’t use throws.
![Page 30: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/30.jpg)
Session 3 - Exception-Handling Java Programming
3030TCS Confidential
The throws clause -continued
Type method-name (parameter-list) throwsexception-list
{ // body of method }
![Page 31: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/31.jpg)
Session 3 - Exception-Handling Java Programming
3131TCS Confidential
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);}}
}
![Page 32: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/32.jpg)
Session 3 - Exception-Handling Java Programming
3232TCS Confidential
Java’s Built-in Exceptions
Java defines several exception classes inside the standard package java.lang
RuntimeException or Error
![Page 33: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/33.jpg)
Session 3 - Exception-Handling Java Programming
3333TCS Confidential
Unchecked ExceptionsUnchecked Exception =
Runtime Exceptions/ERRORExample:
•NumberFormatException•IllegalArgumentException•OutOfMemoryError
![Page 34: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/34.jpg)
Session 3 - Exception-Handling Java Programming
3434TCS Confidential
Checked ExceptionsChecked Exception = checked at
compile time
These errors are due to external circumstances that the programmer cannot prevent Example:-IOException
![Page 35: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/35.jpg)
Session 3 - Exception-Handling Java Programming
3535TCS Confidential
Java’s Built-in Exceptions ...The following are Java’s CheckedExceptions:
ClassNotFoundExceptionCloneNotSupportedExceptionIllegalAccessExceptionInstantiationExceptionInterruptedExceptionNoSuchFieldExceptionNoSuchMethodException
![Page 36: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/36.jpg)
Session 3 - Exception-Handling Java Programming
3636TCS Confidential
PRELUDEGarbage collection ,
User defined Exceptions, Assertions,
chained Exceptions
![Page 37: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/37.jpg)
Session 3 - Exception-Handling Java Programming
3737TCS Confidential
The Utility of Backtracking
Backtracking is the process bywhich the stack frame isunwound in the presence of anunhandled exception.
Objects created on the stack are discarded to the GC.
![Page 38: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/38.jpg)
Session 3 - Exception-Handling Java Programming
3838TCS Confidential
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()’.
Garbage Collection
![Page 39: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/39.jpg)
Session 3 - Exception-Handling Java Programming
3939TCS Confidential
It is called with neither timingnor order guaranteedTo ensure that the resources
are freed finalize() method.****System.gc();protected void finalize(){ //finalization code}
![Page 40: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/40.jpg)
Session 3 - Exception-Handling Java Programming
4040TCS Confidential
Creating Your Own Exception Classes
All user-created exceptions –subclass of ExceptionAll methods inherited Throwable.
![Page 41: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/41.jpg)
Session 3 - Exception-Handling Java Programming
4141TCS Confidential
Demo of ExcepDemo.javaclass YourException extendsException{ private int detail;
YourException(int a) { detail = a; }public String toString( )
{return “YourException[“ + detail +”]”; }}
![Page 42: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/42.jpg)
Session 3 - Exception-Handling Java Programming
4242TCS Confidential
class ExcepDemo {static void compute(int a)
throwsYourException{
if( a > 10) throw newYourException(a);System.out.println(“Normal Exit”)
}
![Page 43: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/43.jpg)
Session 3 - Exception-Handling Java Programming
4343TCS Confidential
ExcepDemo.java ...
public static void main(String args[ ]){try { compute(1); compute(20);}
catch(YourException e){System.out.println(“Caught“+e)}} }
![Page 44: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/44.jpg)
Session 3 - Exception-Handling Java Programming
4444TCS Confidential
Output:Called compute(1)Normal exitCalled compute(20)Caught YourException[20]
![Page 45: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/45.jpg)
Session 3 - Exception-Handling Java Programming
4545TCS Confidential
AssertionsAssertions are conditions
that should be true at a particular point in a method.
Assertions can be validated using the assert statement
![Page 46: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/46.jpg)
Session 3 - Exception-Handling Java Programming
4646TCS Confidential
Assertions
assert statementEvaluates -true or falseassert exp;AssertionError if exp falseassert exp1 :exp2; exp2 is error message
![Page 47: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/47.jpg)
Session 3 - Exception-Handling Java Programming
4747TCS Confidential
By default, assertions are disabledAssertions can be enabled
with the –ea command-line option
![Page 48: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/48.jpg)
Session 3 - Exception-Handling Java Programming
4848TCS Confidential
assert (number>=0&&number<=10):"bad number"+ number
If you enter a number 50
Exception in thread "main" java.lang.AssertionError:bad number:50
![Page 49: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/49.jpg)
Session 3 - Exception-Handling Java Programming
4949TCS Confidential
Chained ExceptionsAssociate one exception withanother.
Second exception describes the cause of the first exception.initCause(Throwable cauExc)getCause()
![Page 50: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/50.jpg)
Session 3 - Exception-Handling Java Programming
5050TCS Confidential
static void demo(){NullPointerException
e=newNullPointerException(“Top”);e.initCause(newArithmeticException(“cause”));
throw e;}e.getCause();NullPointerException,Original Cause
ArithmeticException.
![Page 51: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/51.jpg)
Session 3 - Exception-Handling Java Programming
5151TCS Confidential
When to Use ExceptionsDeal with the exception try
and catch.Pass the exception up the
calling chain by adding throwsclause
Both by catching the using catch and then explicitly rethrowing it using throw
![Page 52: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/52.jpg)
Session 3 - Exception-Handling Java Programming
5252TCS Confidential
When Not to Use ExceptionsWhen 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.
![Page 53: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/53.jpg)
Session 3 - Exception-Handling Java Programming
5353TCS Confidential
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.
![Page 54: Exception-Handling Java Programming - Gujarat Informatics Limited](https://reader031.fdocuments.us/reader031/viewer/2022021210/62064b8a8c2f7b17300659f4/html5/thumbnails/54.jpg)
Session 3 - Exception-Handling Java Programming
5454TCS Confidential
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 compilerThe level of analysis the compiler performs, are usually not sufficient to establish that such runtime exceptions cannot occur.