0% found this document useful (0 votes)
15 views23 pages

Exception Handling

The document provides an overview of exception handling in programming, defining exceptions and their types, including checked and unchecked exceptions. It explains the use of try-catch blocks, the runtime stack, and various keywords like throw and throws for managing exceptions. Additionally, it discusses enhancements in exception handling introduced in Java 1.7, such as try-with-resources and multi-catch blocks, along with the concept of exception propagation and rethrowing exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views23 pages

Exception Handling

The document provides an overview of exception handling in programming, defining exceptions and their types, including checked and unchecked exceptions. It explains the use of try-catch blocks, the runtime stack, and various keywords like throw and throws for managing exceptions. Additionally, it discusses enhancements in exception handling introduced in Java 1.7, such as try-with-resources and multi-catch blocks, along with the concept of exception propagation and rethrowing exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Exception

Handling
- Harshwardhan
Zade
Exception:
An unexpected unwanted event that disturbs normal flow of program is called Exception.
Ex:-
TyrePuncturedException  Real world Example
SleepingExcepion  Real world Example
FileNotFoundException
Exception Handling:-
Handling the unexpected event in order for the smooth execution of program is known as
Exception Handling. Exception handling does not mean repairing an exception, we have
to provide alternative way to continue rest of the program. Normally, is the concept of
exception handling.
An exception can be handled using try-catch block.
Ex:- try{
//Risky code
}
catch(exception e){
//Handling code
}
RunTime Stack:-
1.For every thread, JVM will create 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 is called 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

RunTime Stack
Ex:-
public class RuntimeStackDemo {
public static void main(String[] args) {
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println("Hello");
}
}
o/p:-
Hello
Default Exception Handling:-
Inside a method, if any exception occurs, the method in which it is
raised is responsible to create exception object by including the
following information:
1. Name of Exception
2. Description of Exception
3. Location at which Exception occurs (Stack Trace)
Ex:-
public class Demo1 {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
doMoreStuff();
}
public static void doMoreStuff() {
System.out.println(10/0);
}
}
Exception Hierarchy:-

Throwable

Exception Error

RemoteExcption
IoException
RunTimeException ServletException
VM Error
Assertion
EofException
ArithmeticException Error
FileNotFoundException
NullPointerException Exception in
InterruptedException Initialisation Error
Stack Overflow
ClasscastException
Error
IndexOutOfBoundException Out of Memory
ArrayIndexOutOfBoundException Error
StringIndexOutOfBoundException
IllegalArguementException
NumberFormatException
Checked Exception vs Unchecked Exception:-
The exception which are checked by the compiler for smooth execution of
the program at runtime are called checked exception.
Ex:-
1. HallTicketMissingException
2. PenNotWorkingException
3. FileNotFoundException

The exception which are not checked by the compiler whether programmer is
handling or not such type of exception is called unchecked exception.
Ex:-
1.ArithmeticException
2.BombBlastException
Fully checked vs Partially checked:-
A checked is said to be fully checked if and only if all its child classes are also
checked.
Ex:- IOException & InterruptedException

A checked exception is said to be partially checked if and only if some of its


child classes are unchecked.
Ex:-
Throwable & Exception are example of partially checked exceptions.

Methods to print Exception information:-


Methods Data
printStackTrace() Name of Exception
Description
Stack Trace
toString() Name of Exception
Description
getMessage() Description
Various possible combinations of try-catch&finally:-
1.In try catch finally, order is important. Whenever we are writing try
compulsory, we should write either catch or finally otherwise we will
get compile time error. try without catch or finally is invalid.

2.Whenever we are writing catch block compulsory try block must be


required i.e., catch without try is invalid.

3.Whenever we are writing finally block compulsory we should write


try-block i.e., finally without try is invalid.

4.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.
Case:1 Case:2 Case:3 Case:4
try{ try{
//Valid try{ try{
//Valid
} //Invalid //Valid
}
catch(exception e){ //Already caught }
catch(x e)
} } catch(){
{
catch(x e){ }
}
} finally(){
catch(y e)
catch(x e) }
{
{
}
}
Case:5 Case:6 Case:7 Case:8 Case:9 Case:10
try{ try{ try{ try{ catch(){ finally(){
//Valid //Valid //Valid //Invalid //Invalid catch //Invalid finally
} catch(){ } //try without without try without try
finally(){ } catch(){ catch or } }
} } } finally
try{ try{ }
catch(){ }
} finally(){
} }
Case:11 Case:12 Case:13 Case:14
try{ try{ try{ try{
//Invalid //Invalid //Invalid //Invalid
//catch without try //catch //catch without try //finally without try
} without try } }
finally(){ } catch(x e){ catch(){
} S.O.P(“Hi”) } }
catch(){ catch(){ S.O.P(“Hi”) S.O.P(“Hi”)
} } catch(y e){ finally(){
} }
Case:15
try{
//valid
catch(){
}
}
try{
}
catch(){
}
throw keyword:-
=>The main use of throw keyword in java is to create the exception object and handover it to the
JVM manually.
=>The other use of throw keyword is to customize the exception.
Ex:-class demo{
public static void main(String[] args){
throw new ArithmeticException(/by zero);
}
}
Case:1
public class Demo {
static ArithmeticException e;
public static void main(String[] args) {
throw e;
}
}
Output: -
Exception in thread "main" java.lang.NullPointerException: Cannot throw exception because
"com.exception.handling.Demo4.e" is null
at com.exception.handling.Demo4.main(Demo4.java:6)
Case:2
After throw statement we are not allowed to write any statement directly otherwise we will get compile time error
saying unreachable statement.
Ex:-
public class Demo4 {
public static void main(String[] args) {
throw new ArithmeticException(/by zero)
System.out.println("Hello");
}
}
Output: -Exception in thread "main" java.lang.ArithmeticException: / by zero at
com.exception.handling.Demo4.main(Demo4.java:5)
Case:3
We can use throw keyword only for throwable types if we are typing to use for normal java objects, we will get compile
time error saying incompatible types.
Ex:-
public class Demo4 {
public static void main(String[] args) {
throw new Demo4();
}
}
throws keyword:-
In our program if there’s a possibility of raising Checked Exception then compulsory, we should
handle that Exception otherwise we will get Compile time Error saying UnreportedException XXX
must be caught or declared to be thrown.
Ex:-
import java.io.PrintWriter;
public class Demo4 {
public static void main(String[] args) {
PrintWriter pw = new PrintWriter("abc.txt");
pw.println("Hello world");
}
throws keyword required only for Checked Exception and uses of throws for Unchecked Exception
there is no use or there is no Impact.
throws keyword is only required to convince compiler and uses of throws keyword does not prevent
abnormal termination of the program
Exception Handling Keywords Summary
1. try: - To maintain Risky code.
2. catch: - To maintain Exception Handling code.
3. finally: - To maintain cleanup code.
4. throw: - To handover our created Exception object to the JVM.
5. throws: - To delegate responsibility of Exception handling to the caller.
Various possible compile time error in Exception Handling
6. UnreportedException XXX; must be caught or declared to be thrown.
7. Exception XXX has already been caught.
8. Exception XXX has never thrown in body of corresponding try statement.
9. Unreachable Statement
10.Incompatible Types
found: Test
required: java.lang.Throwable
6. try without catch or finally
7. catch without try
8. finally without try
Customized or user defined Exception
Sometimes to meet programming requirement we can define our own Exception such types of Exception are
called Customized or User defined Exceptions
Ex:-
import java.util.Scanner;
class TooYoungException extends RuntimeException{
public TooYoungException(String s) {
super(s);
}
}
class TooOldException extends RuntimeException{
public TooOldException(String s) {
super(s);
}
}
public class Demo4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter your age: ");
int age = sc.nextInt();
if(age > 60) {
throw new TooOldException("You already crossed
marriage age... No chance of getting married");
} else if(age < 18) {
throw new TooYoungException("You are too
young to get married");
} else {
System.out.println("You will get matched details
very soon in Mail");
}
}
}
JVM Exceptions
1. ArrayIndexOutOfBoundException: -
It is child class of RuntimeException and it is Unchecked.
Raised automatically by JVM whenever we are trying to access
elements with out-of-range Index.
2.NullPointerException: -
It is child class of RuntimeException and it is Unchecked.
It is raised automatically by JVM whenever we are trying to
perform any Operation on null.
3.ClassCastException: -
It is child class of RuntimeException and hence it is Unchecked
Raises automatically by JVM whenever we are trying to typecast
Parent Object to child type.
4.StackOverflowError: -
It is the child class of Error and hence it is Unchecked.
Raised automatically by JVM whenever we are trying to perform
recursive method calls.
5.NoClassDefFoundException: -
1. It is the child class of Error and hence it is Unchecked.
2. Raised automatically by JVM whenever JVM is unable to find
required .class file.
3. If Test class file is not available saying NoClassDefFoundException.
6.ExceptionInInitializerError: -
It is the child class of Erro and hence it is Unchecked.
Raised automatically by JVM if any Exception occurs while executing static
variable assignments and static block.
7.IllegalArgumentException: -
It is the child class of RuntimeException and hence it is Unchecked.
Automatically raised by programmer or API developer to indicate that a
method has been invoked with Illegal Argument.
8.NumberFormatException: -
It is the child class of IllegalArugmentException which is the child class of
RuntimeException and hence it is Unchecked.
Raised explicitly either by Programmer or API developer to indicate that we
are trying to convert String to number and the String is not properly formatted.
9.IllegalStateException: -
1. It is the child class of RuntimeException and hence it is Unchecked.
2. Raised explicitly by Programmer or API developer to indicate that a method has
been invoked at wrong time.
After starting of a Thread, we are not allowed to restart the same Thread once again
otherwise we will get RuntimeException saying IllegalThreadStateException.
10.AssertionError: -
It is the child class of Error and hence it is Unchecked.
Raises automatically by the programmer or API developer to indicate that Assert
statement fails.
E.g.,
assert (x > 10);
If x is not greater than 10 then we will get RuntimeException saying AssertionError.
1.7v. Enhancement with respect to Exception Handling
1. As a part of 1.7v Enhancement in Exception Handling the following two concepts are
introduced.
1. try with resources
2. Multi – Catch Block
Try with resources
2. Until 1.6v, it is highly recommended to write finally block to close resources which are
opened as a part of try block.
3. The issues with the above approach are that the programmer is forced to close resources
inside the finally block, which increases the program's complexity.
4. To overcome the previous problem, Sun Microsystem introduced try with resources in 1.7v.
The key advantage of try with resources is that whatever resources we open as part of the
try block will be closed automatically.
5. Once control reaches the end of the try block, whether normally or abnormally, we are not
needed to close explicitly, reducing program complexity.
6. We are not required to write a finally block, which shortens the code and improves
readability.
Multiple Catch Block
1. Until 1.6v, even if several different exceptions share the same handling code, we had to write a
separate catch block for each exception type. It lengthens the code and reduces readability.
2. To overcome these problem Sun Mircrosystem introduced multi catch block in 1.7v according to
this we can write a single catch block that can handle multiple different types of Exceptions.
3. The main advantage of this approach is length of the code will be reduced & readability of the code
will be improved.
4. In the above example, the above expression is either ArithmeticException or NullPointerException,
the same catch block can respond.
5. In multi catch block there should not be any relation between exception type either child to parent or
same type otherwise we will get Compile time Error.
try {

}
catch (ArithmeticException | IOException e) {
e.printStackTrace();
} catch (NullPointerException | InterruptedException e) {
System.out.println(e.getMessage());
}
Exception Propagation
Inside a method if an Exception raised & if we are not handling that exception then exception
object will be propagated to caller. Then caller method is responsible to handle exception this
process is called Exception propagation.
Ex:-
m2()
m1()
{
{ S.O.P(10/0); //Exception
m2(); }
}
Rethrowing Exception:
1. We can use this approach to convert one Exception type to
another Exception type.
public class Demo5 {
public static void main(String[] args) {
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
throw new NullPointerException();
}
}

You might also like