0% found this document useful (0 votes)
105 views57 pages

ExceptionHandling PDF

Exception handling allows a program to gracefully handle errors and exceptions to maintain continuous flow. There are different types of exceptions like checked and unchecked. Try/catch blocks are used to handle exceptions where the try block contains code that might throw an exception, and catch blocks provide alternative code if exceptions occur. Finally blocks are used to execute code whether an exception occurs or not. Exceptions can be rethrown within catch blocks to propagate the exception.

Uploaded by

Jesse
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)
105 views57 pages

ExceptionHandling PDF

Exception handling allows a program to gracefully handle errors and exceptions to maintain continuous flow. There are different types of exceptions like checked and unchecked. Try/catch blocks are used to handle exceptions where the try block contains code that might throw an exception, and catch blocks provide alternative code if exceptions occur. Finally blocks are used to execute code whether an exception occurs or not. Exceptions can be rethrown within catch blocks to propagate the exception.

Uploaded by

Jesse
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
You are on page 1/ 57

EXCEPTION HANDLING:

If we need a graceful termination of a program.


(ie not having any kind of data termination).

INTRODUCTION TO EXCEPTION HANDLING:


An alternatig way to maintain the program’s continuous flow of
program.

DEFAULT EXCPETIONAL HANDLING:

THe method where the exception occurs is responsible for that


exception.....”obviously”....with the help of jvm it creates the object
of ecxception....
Exception format:
Exception name:”description of exception”
Stack trace:/location:at which method
Caller of method
Caller of ,method.

Eg:
Suppose there is an Exception in main thread....
We have exceptioj as follows :
Exception in thread main:java.lang.Arithemetic Exception:division
by Zero
At somemethod();
“““““““ ““
“ “ “” ”” ” ””
“ ” “” “ “” “” “

Throwable class acts as root class for java hirarchy.

Exceptions are recoverable.(ie are we able to handle the


ecxeption)…...ie known as recoverable.

Errors are non recoverable.


CHECKED VS UNCHECKED EXCEPTIONS:
Eg:
import java.io.PrintWriter;

public class TestException {


public static void main(String[] args) {
PrintWriter pw=new PrintWriter("abc.text");//checked
exception …..to handle...
pw.print(10);
}
}
Eg:

public class ThreadException {


public static void main(String[] args) {

System.out.println("Haiiiiii");
Thread.sleep(1000); //interrupted exception

}
}
All the sub-classes of exception class except “RUNTIME
EXCEPTION” is checked exception......including the ERROR
class...and all of its sub classes.

FULLY CHECKED VS PARTIALLY CHECKED EXCEPTION:

If the parent class is checked and its child class is also checked
We say it is fully checked

Eg:
IOexception(checked)(parent)
.FilenotFoundEXception(child)(checked)
PARTIALLY CHECKED exceptions are those in which parent
class is checked but its child classes maybe unchecked...its is said
to be partial....
Eg:
Throwable class
Exception class....

EXAMPLE PROGRAM

public class TestwaExceptionwa {


public static void main(String[] args) {
System.out.println("hello luv");
//System.out.println(10/0);
//exception occurs here the program terimnates abnormally
//if we use handling code we have
try {
System.out.println(10/0);// this is known as risky code
//ie the code at which exception might occur
}
catch (ArithmeticException e) {
System.out.println("cannot divide a number by zero");
//this is an alternative code ....or handling code
}
System.out.println("hello again luv")
}
}
METHODS TO PRINT EXCEPTION INFORMATION
e.printStackTrace();
System.out.println(e);
System.out.println(e.getMessage());

Throwable has these 3 methods......

Try with multiple catch blocks


Purpose and Speciality of finally block
Return vs finally block
If try and catch and finally have
return.....priority is given to finally’s return

The only senario where finally block wont


be executed is.....when we explicitly exit the
jvm...ie(stop jvm)
By using System.exit(0);....(here zero is
status code used by jvm.....if code is 0 it
means noramal termination and non-zero
number means ….abnormal termination)
Note: the effect will remain the same.at logs
leve;..ie server log or processor log..”why” did
jvm shut down...for that purpose
Eg 2:
Same output in both exmaples

CONTROL FLOW IN try –catch – finally


If risky code is not surrounded by
“try” then always the program is
terminated abnormally.
Nested try and catch block
CONTROL FLOW IN nested try catch finally
We cannot write finally block without try
and catch
Eg:

public class ExceptionFinally {


public static void main(String[] args) {
System.out.println(10/0);

// try {
// System.out.println(10/0);
// } catch (Exception e) {
//
// System.out.println("cannot divide a
number by zero");
// }
//(compile time error finally {
System.out.println("hello beautiful");
}
}
}
CASES FOR CONTROL FLOW
VARIOUS POSSIBLE COMBINATIONS OF try
catch and finally
Throw keyword
Output:
Output:
Case2:
If any code written after throw will become
unreachable.....even return return statement
cannot be written.

public class ExceptionFinally {


public static void main(String[] args) {
check();

static int check() {

throw new ArithmeticException();


return 7;

}
}

CASE:3
public class ExceptionFinally {
public static void main(String[] args) {
throw new ExceptionFinally();//complie
time error

}
}
As we can see ExceptionFinally is not a
subclass of Throwable class hence we get
compile time error.
To over come this just extend the class by
Any of the subclasses of Throwable......ie
Eg:
public class ExceptionFinally extends
RuntimeException {
public static void main(String[] args) {

throw new ExceptionFinally();

}
}
Now here there is a catch “only unchecked
exceptions it can extend......(not that it
cannot extend checked exceptions....but
we’ll have to handle it as complier will know
there is a chance of exception).
Eg:
If we use Throwable class or exception class
we have:
public class ExceptionFinally extends
Exception {
public static void main(String[] args) {

throw new ExceptionFinally();//unhandled


exception.
}
}
Throws keyword:
Throws keyword is not used with class
It is only applicable to methods and
construcotrs.
Need for super() in …...
Types of exception(top 10)
ARRAY OUT OF BOUND:
It is the child class of index out of bound exception.
Which is the child class of runtime exception
Which is the child class of exception...

Null pointer exception:


Whenever we perform any operation on null we get
null pointer exception.
StackOverFlow Error :
Whenever we perform recursive method call we may
get these error....
Ie inside the stack every method call is stored as a an
entry ...if the method dosent end...then we get an error
Class cast Exception:
NoClassDefFound error:

ExceptionInInitializer Error:
ILLegalArgumenyException(unchecked)
Number format exception:

(unchecked) immediate child class of illegalargumentexception


IllegalStateException :

(unchecked)

Calling a method at wrong time.....raises this exception


AssertionError:

We get this when we perform debugging when we use assertion statement ….and this statemnt fails.

Try with Resources:Try with Resources:

(Available since java 1.7)

(Multi catch block.)


There are two problems with this approach........to overcome this we use try with resources

WITH TRY WITH reources ...we do not have to write a finally block to close resources will automayically be closed...
Important points wrt try with resources
• We can juse any number of resources in try block but they msut
be separated by comma

• Whatever resources used with this trty should be autocloaseable...ie any resource or corresponding class
implements autocloseable interface is known a autocloasebale

• ALL DATABASE RESOURCES,NETWORK RELATED REAOURCES,IO RESOURCES ARE AUTOCLOSEABLE.(they already


implements java.lang.autoCloasable )
• It was introduced in 1.7 v
• And it contains only one method in it ie
• Public void close() throws Exception{
• }
• All resources reference variables used are implicitly final .we get compile time error if we try to asign it with new
resources.


• From 1.7 version only try with resource xan be written


• Notes:
Complusory all resources should be include within try.(in 1.7 or 1.8)versions

For 1.9v it is valid

Multi catch block


Eg:

Note:
there should not be any relation between the exceptins in catch block

We get compile time error

EXCEPTION PROPAGATION AND RE THROWING AN


EXCEPTION
caller handling the exception is known as exception propagation.

Re throwing exception:

You might also like