Exception Handling
Exception Handling
1> Introduction
2> Run time stack mechanics
3> Default exception handlining in java
4> Control flow in try catch
5> Control flow in try catch
6> Methods to print exception information
7> Try with multiple catch block
8> Finally block
9> Difference between final, finally finalize
10> Control flow in try catch finally
11> Control flow in nested try-catch-finally
12> Various possible combination of try catch finally
13> Throw keywords.
14> Throws keywords.
15> Exception handling keywords summery
16> Varius possible compile time error in exception
17> Customized or used defined exception
18> Top 10 exception
19> 1.7 version enhancement
➢ Try with resource
➢ Multi catch blocks
Exception:
Example:
TyreePancherd exception
Sleeping exception
1|Page
Example:
Our program requirement is to read data from remote file locating at London at
runtime if London file is not available our program should not be terminate
abnormally we provide some local file to control rest of the program normally
this way of defining alternative is nothing but exception handling.
Try{
Located at London
Catch (fileNotFoundException e) {
1> for every thread ,JVM will crate a runtime stack each and every method
call performed by that thread will be stored in the corresponding stack.
2> Each entry in the stack frame or activation record.
3> After completing every method call the corresponding entry from the
stack will be removed.
4> After completing all method calls the stack will be destroyed by JVM
just before terminating the thread.
public class demo {
public static void main(String[] args) {
dostuff();
}
}
Output:
hello
2|Page
Default exception handling:
➢ Name of exception
➢ Description of exception
➢ Location at which exception occurs(stack trace)
After creating exception object method handovers that object to the JVM.
JVM will check whether the method contains any exception handling code or
not.
If the caller method handling code ,then JVM terminates that caller method
also abnormally and removes corresponding entry from stack.
This process will be continued until main method and if the main method also
does not contain handling code, then JVM terminates main method also
abnormally and removes corresponding entry from the Stack.
Default exception handler prints exception information inn the following format
and terminates program abnormally.
Stack Trace
3|Page
public class demo {
public static void main(String[] args) {
dostuff();
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/revision.demo.doMorestuf(demo.java:13)
at excelr/revision.demo.dostuff(demo.java:9)
at excelr/revision.demo.main(demo.java:5)
package revision;
}
Output:
Hello
Hi
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/revision.demo.main(demo.java:6)
4|Page
public static void main(String[] args) {
dostuff();
}
}
Output:
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/revision.demo.dostuff(demo.java:10)
at excelr/revision.demo.main(demo.java:5)
Note:
Exception Hierarchy:
Exception:-
most of the times exception are caused by our program and this is
recoverable.
Example:
5|Page
Error:-
1. Most of the time error are not occurred by our program and these are
due to lack of system resources.
2. Errors are non-recoverable.
Example:
The exception which are checked by the compiler for smooth execution of the
program at runtime are called checked exception
Example:
➢ HallTicketMissingException
➢ PenNotWorkingException
➢ FileNotFoundException
6|Page
The exception which are not checked by the compiler whether programmer is
handling or not such type of exception is called unchecked exception.
Example:
➢ ArithmaticException
➢ BombBlastException
Runtime exception and its child classes error and its child classes are unchecked
except this remaining are unchecked.
A checked is said to be fully checked if and only if all its child classes are also
checked .
Note: the only partially checked exception in java are exception and throwable.
1> IOException→checked(fully)
2> RuntimeException→unchecked
3> InterruptedException →checked(fully)
4> Error→unchecked
5> Throwable →checked (partially)
6> ArithmaticException →unchecked
7> NullPointerException →Unchecked
8> Exception →Checked Partially
9> FileNotFoundException→checked(fully)
7|Page
The code which may raise an exception that code is called risky code and we
have to define that code in try block and corresponding handling code we have
to define in catch block
try {
//risky code
}
catch(Exception e) {
//handling code
}
Code without try catch:
public class exceptiondemo {
}
Output:
statement 1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/Tulalu.exceptiondemo.main(exceptiondemo.java:7)
abnormal termantion
}
System.out.println("statement 3");
}
}
Output:
statement 1
5
statement 3
normal termination
8|Page
Control flow in try catch
try {
statement 1;
statement 2;
statement 3;
}
catch(Exception x) {
statement 4;
}
statement 5;
case1:
if there is no exception in the above program then the output will be statement
1, 2 ,3 & 5 normal termination.
Case2:
Case3:
Case4:
Note:
Within the try block if any where an exception is raised then rest of the try
block will not be executed even though we handle that exception hence within
the try block we have to take only risky code and length of try block should be
as less as possible.
9|Page
Methods to print Exception Information:-
}
Output:
java.lang.ArithmeticException: / by zero
at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:6)
}
Output:
java.lang.ArithmeticException: / by zero
10 | P a g e
Note: internally default exception handler PrintStackTrace to print exception
information to the console.
The way of handling an exception varies from exception to exception ,hence for
every exception type it is highly recommended to take separate catch block i.e..
with multiple catch block is always possible & recommend to use
11 | P a g e
If try with multiple catch blocks are present then the order of catch block is
very important , we have to take child first otherwise we will get exception
saying Exception XXX has already been caught
package Tulalu;
}
catch(ArithmeticException e) {
}
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ArithmaticException cannot be resolved to a type
at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:11)
}
catch(Exception e) {
}
}
}
correct
we cannot declare two catch blocks for the same exception otherwise we will
get compile time error.
package Tulalu;
12 | P a g e
catch(ArithmeticException e) {
}
}
}
Output: as error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable catch block for ArithmeticException. It is already
handled by the catch block for ArithmeticException
at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:11)
final:-
Finally:-
try {
//risky code
}
catch(Exception e) {
//handling code
}
finally {
//clean up
}
Finalize():-
13 | P a g e
Note:- finally block is responsible to perform cleanup activities related to try
block i.e., whatever resources we opened at the part of try block will be closed
inside finally block.
Whenever we are writing catch block compulsory try block must be required i.e.,
catch without try is invalid.
Whenever we are writing finally block compulsory we should write try-block i.e.,
finally without try is invalid.
Inside try-catch and finally blocks we can declare try catch and finally blocks.
i.e., Nesting of try catch finally is allowed for try catch finally blocks curly
braces are mandatory.
14 | P a g e
17> 18> 19> 20>
Try{ Try{ Try { } Try{ }
Try{} } Catch(x e){ Catch (x e){
Finally {} Catch(x e) Finally{ } }
} { } Finally {
Catch (x e){ Try{ } CE :- finally Try{ }
} Finally { } without Catch(x e){
valid } Catch }
valid Invalid } valid
15 | P a g e
Throw keyword:
Exception object
Some time we can create exception object explicitly we can handover to JVM
manually for this we have to use throw keyword
16 | P a g e
Best use of throw keyword is for user defined exception or customize
exception:
Example:
Case 1:
➢ Throw e;
If e refers to null then we will get NullPointerException();
public class exceptionmethods {
}
}
ERROR:
Exception in thread "main" java.lang.ArithmeticException
at excelr/Tulalu.exceptionmethods.<clinit>(exceptionmethods.java:5)
static ArithmeticException e;
public static void main(String[] args) {
throw e;
}
}
Error:
Exception in thread "main" java.lang.NullPointerException: Cannot throw
exception because "Tulalu.exceptionmethods.e" is null
at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:7)
case 2:
After throw statement we are not allowed to write any statement directly
otherwise we will get compile time error saying unreachable statement.
public class exceptionmethods {
17 | P a g e
Case 3
We can use throw keyword only for throwable types if we are trying to use for
normal java object we will get compile time error saying incompatible type.
public class exceptionmethods {
Throws keyword:
We can handle this compilation error by using the following two ways:
18 | P a g e
2> By using throws keyword
Thread.sleep(100000);
}
}
Throws keywords only required for checked exception and uses of throws for
unchecked exception there is no use ,there is no impact
Throws keyword only required to convince compiler and uses of throws keywords
doesn’t prevent abnormal termination of the program.
package Tulalu;
19 | P a g e
In this above program if we remove at lest one throws statement then the code
will not compile.
Conclusion:
Throws clause
Or
keywords
20 | P a g e
Case1:
We can use throws keyword for method and constructor but not for class.
public class testcase throws Exception { //invalid
testcase()throws Exception //valid
{
public void m1()throwsExcption; //valid
}
Case 2:
We can use throws keyword only for throwable type of we are trying to use
for normal java class then we will get compile time error saying incompatible
type.
public class demoo {
public void m1()throws demoo {
}
Compile time error:
Incompatible type found test found :test required java.lang throwable
Case3:
public class demoo { public class demoo {
public static void public static void main(String[]
main(String[] args) { args) {
throw new throw new Error(); //unchecked
Exception(); }
}
}
} Exception in thread "main"
Unresolved compilation problem: java.lang.Error
Unhandled exception type at
Exception excelr/Tulalu.demoo.main(demoo.java:5)
Case 4:
public class Teest {
public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(Exception e) {
//partially_unchecked
}
}
}
Valid
//output:
// hello
21 | P a g e
public class Teest {
public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(ArithmeticException e) {
//unchecked
}
}
}
o/p: hello
22 | P a g e
with in the try block if there is no chance of raising an exception then we
shouldn’t write the catch block for that exception other wise compile time error
saying xxx never thrown in body of corresponding try statement, but this rule
applicaqble only for fully checked exception.
Import java.util.scanner;
}]
23 | P a g e
package Tulalu;
import java.util.Scanner;
else {
System.out.println("you will get matched details send by
mail");
}
}
}
Top 10 Exceptions:
Based on the person who is raising an exception are divide into two categories:
➢ JVM Exception
➢ ProgrammaticException
JVM Exception:
Arithmetic Exception
NullPointer Exception
Programmatic Exception:
TooOldException
IllegalArgumentException
24 | P a g e
1>ArrayIndexOutOfBoundException:
}
Output:
NullPointerException
3>ClassCastException
Raised automatically by JVM whenever we are trying to type cast parent obj to
child type.
public class classcast {
public static void main(String[] args) {
// String s=new String("tulalu");
// object o=new object();
object o=new object();
String s=(String)o;
}
}
Class cast exception
4>StackoverflowError.
25 | P a g e
public class stackoverflowerror {
public static void m1() {
m2();
}
}
public static void main(String[] args) {
m1();
}
Output:
Runtime Exception saying StackoverflowError
It test class file is not available then we will get runtime exception saying
NoclassException.
6> ExceptionInInitializerError:
}
Exception thread main java.lang.exception on intntialtilizerError caused by
javala.lang Aritmatic error / by zero
}
Re saying null pointer exception
26 | P a g e
7>IllegalArgumentException:
}
Re saying illegalArugmentException
8>NumberFormateException:
10>AssertionError:
27 | P a g e
Example:
Assert(x<);
ArrayindexoutoFBoundException
NullPointerException
ClassCastException Raised automatically by JVM exception &
Stack overflow error there are JVM exception
noclassdefException
exceptioninitializerError
illegalArgumentException
NumberfromateException
Raised Explicitly eaither by programmer or by API
IllgalThreadstateException developer & hence these are programmatic
AssertionError execption
1.7 version
28 | P a g e
Conclusions:
Try(r1;r2;r3)
Fr fr=new fr(“input.txt”)){-→ r2
All IO resources ,database, related resources & network related resources are
already implemented auto closeable interface.
Auto closeable interface came in 1.7v & contains only one method i.e close().
Try(r1;r2;r3){
➢ Auto closeable
➢ Java .lang .Auto closeable
➢ 1.7 version
➢ Close ()
All resources reference variable are implicitly final & hence with in the try
block we cant perform reassignment otherwise we will get CE.
Import java.io.*;
Main(){
29 | P a g e
Until,1.6 version try should be associated with either catch or finally but from
1.7 version onwards we can take only try without catch or finally.
Catch or finally
Try(R){
------
-----
The main advantage of try with resources is we are required to write finally
blocks explicitly because we are not required to close resources explicitly until
1.6 v finally block will be like hero but 1.7 version onwards it becomes zero.
Until 1.6 even thought multiple different exceptions having same handling code
for every exception type we have to write a separate catch block it increases
length of the code & reduced readability.
Try{-----}
Catch(AE e){
e.printStackTrace();
e.printStackTrace();
Sop(e.getMessage));
Catch(interuptedException e)
Sop(e.getMessage());
30 | P a g e
To overcome these problem sun people introduced multi catch block in 1.7
version according to this we can write a single catch block that can handle
multiple different types of exceptions.
Try{
----
Catch(AE/io exception e)
e.printStackTrace();
Sop(e.getmessage());
The main advantages of this approach is length of code will be reduced &
readability of the code will be increased.
public class multicatch {
public static void main(String[] args) {
try {
// System.out.println(10/0);
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException |NullPointerException e) {
System.out.println(e);
}
}
}
In the above example wither raised exception is either ArithmeticException or
NPE the same catch block can respond in multi-catch block there shouldn’t be
any relation between exception type either child to parent or parent to child or
same type otherwise we will get compile time error.
try {
//statenment
}
catch(ArithmeticException |Exception e) {
31 | P a g e
Exception propagation:
m1(){
m2(){
Rethought Exception:
We can use this approach to convert one exception type to another exception
type.
public class rethroug {
public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {
throw new NullPointerException();
}
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at excelr/exception_types.rethroug.main(rethroug.java:9)
32 | P a g e