EXCEPTION HANDLING:
It is an unexpected, unwanted event which describe or disturbs the normal flow of execution.
It is an unexpected unwanted event triggered in the JVM which makes the JVM to terminate the
program abnormally.
DIFFRENCE BETWEEN ERROR AND EXCEPTION:
ERROR EXCEPTIONS
• Exceptions can be recovered. • Errors cannot be recovered.
• Exceptions can be classified into two types • Errors are mainly classified in to two types
1. Checked Exception 1. Compile time error
2. Unchecked Exception 2. Run time error
• In case of Checked exception compiler • In case of errors compiler won’t have
Will have knowledge of checked exception knowledge of errors.
And force to keep try catch blocks
❖ Compile time errors are those type of errors which are caught by the compiler during
compilation time.
❖ Compile time errors are mainly because of syntax mistakes.
❖ Runtime errors are those errors which are caught by the JVM during run time.
❖ Exceptions are one of the example of runtime errors
TYPES OF TERMINATIONS:
system.exit (0)
X X
Normal Termination Forceful Termination Abnormal Termination
EXCEPTION HIERARCHY
DEFAULT EXCEPTION HANDLER:
❖ When ever there is an exception in a program, JVM will create an object of respective type
of exception and throws back to the program if programmer doesn’t written any code to
handle then default exception handler will handle the exception object.
❖ Default exception handler will first terminate program abnormally and display the exception
to the programmer
EXAMPLE:
public class ExceptionDemo1
{
public static void main(String[] args)
{
System.out.println("Main method started");
int x = 10, y = 0;
System.out.println(x/y);// exception line
System.out.println("Main method ended");// not executed
}
}
/*
Main method started
Exception in thread "main" java.lang.ArithmeticException: / by zero*/
In order to ensure the normal termination, we need to handle the exception by using handlers.
1. Try
2. Catch
3. Throw Handlers
4. Throws
5. Finally
TRY CATCH BLOCK:
❖ It usually contains only those line of code which may cause an exception once the exception
occurs in try block JVM will create respective exception object and throws it. Programmer
should have written corresponding catch block to catch the exception thrown from the try
block.
❖ Once the control jumps from try to catch block it will not come back again. Hence all the
lines of code present below the exception line will not execute.
❖ Just because we have written try block it doesn’t mean exception will always occurs. If
exception occurs catch block will execute other wise it will not execute.
EXAMPLE:
public class ExceptionDemo2
{
public static void main(String[] args)
{
System.out.println("Main method started");
int x = 10, y = 0;
try
{
System.out.println("Entering try block");
System.out.println(x/y); // exp line
System.out.println("Exiting try block");
}
catch (Exception e)
{
System.out.println("Entering catch block");
System.out.println(e.getMessage());
System.out.println("Exiting catch block");
}
}
}
/*
Main method started
Entering try block
Entering catch block
/ by zero
Exiting catch block
*/
TRY WITH MULTIPLE CATCH:
A try block can have any no of catch block depending upon the type of exception occurred from
try block respective catch block will executed if the exception object is not matching with any
catch block then default exception handler will handle.
*** from one try block at most one exception can occur.
EXAMPLE:
public class ExceptionDemo3
{
public static void main(String[] args)
{
int[] a = new int [10];
try
{
System.out.println("Entering try block");
System.out.println(a[10] = 10);// exception line
System.out.println("Exiting try block");
}
catch (ArithmeticException e)
{
System.out.println("Entering catch block of AE");
System.out.println(e.getMessage());
System.out.println("Exiting catch block of AE");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Entering catch block of AIOBE");
System.out.println(e.getMessage());
System.out.println("Exiting catch block of AIOBE");
}
}
}
/*
Entering try block
Entering catch block of AIOBE
10
Exiting catch block of AIOBE
*/
Try
Catch (ArithmeticException e)
Catch (NullPointerException e) Specialized Try Generalized
Catch (FileNotFoundException e) Catch block Catch (Exception) Catch block
Catch (Null e)
EXAMPLE:
try try
{ {
System.out.println(10/0); System.out.println(10/0);
} }
catch (ArithmeticException e) catch (Exception e)
{ {
------ ------
} }
catch (Exception e) catch (ArithmeticException e)
{ {
------ ------ // code unreachable
} }
Specialized catch block Generalized catch block
We can write generalized catch block and specialized catch block together, but the order should
be first specialized and then generalized.
MULTIPLE TRY CATCH BLOCK:
This is used to handle multiple exceptions.
EXAMPLE:
public class ExceptionDemo4
{
public static void main(String[] args)
{
int x = 10, y = 0;
int[] a = new int [10];
try
{
System.out.println(x/y); // exception line
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException catch block");
}
try
{
System.out.println(a[10] = 10); // exception line
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException catch
block");
}
}
}
/*
ArithmeticException catch block
ArrayIndexOutOfBoundsException catch block
*/
THROW KEYWORD:
❖ It is a keyword used to throw exception object explicitly.
❖ Using throw keyword, we can throw both checked and unchecked exception one at a
time.
❖ Throw can throw only those exceptions objects which contains properties of throwable
throw new IO Exception ( ); already contain throwable.
throw new SQL Exception ( );
throw new NotEligibleToMarry ( ); valid only if it contain the property of throwable
throw new NotEligibleForInterview ( );
❖ Throw must be used inside the definition.
EXAMPLE:
try try
{ {
System.out.println("Hi"); System.out.println("Hi");
System.out.println(10/0); throw new ArithmeticException();
System.out.println("Bye"); System.out.println("Bye");
} }
catch(Exception e) catch(Exception e)
{ {
e.getMessage(); e.getMessage();
} }
Decision done on run time and Decided on compile time and
execute on runtime. executed on runtime.
THROW THROWABLE
❖ It is a keyword it is an exception class
❖ Written to throw exception explicitly.
EXCEPTION PROPOGATION:
When an exception occurs in any method JVM will create a respective type of object and throws
it back to the respective method if programmer as not written any code to handle. The exception
object will automatically propagate to the caller. This propagation will continue till the JVM and
leads to abnormal termination.
Automatic propagation will take place when only if the exception
is unchecked. If its checked then we should use “throws” keyword.
THROWS KEYWORD:
❖ It is a keyword used to propagate checked exception object back to the caller.
❖ Throws must be used inside the method declaration.
❖ Using throws we can inform the caller about multiple checked exception to the caller.
Example:
public static void print() throws SQLException iOException InterruptedException
{
}
❖ Throws can be used to propagate unchecked propagation also, but it is not recommended
to you, because unchecked exceptions can propagate themselves.
Example: public static void print() throws ArithmeticException Not Required.
CHECKED EXCEPTION UNCHECKED EXCEPTION
• Known at compile time and occurs at • Known and occurs both at the runtime.
run time.
• They will not propagate automatically. • It will propagate automatically.
• Throws keyword is required. • Throws keyword is required.
THROW THROWS
• It is a keyword used to throw checked • It is a keyword used to propagate checked
and unchecked objects. exception.
• Should be used inside body • Should be used in the method declaration.
• Can throw only one exception object • Throws keyword can associate multiple
at a time. checked exception.
FINALLY KEYWORD:
❖ Finally block usually contains closing related operations like closing the opened
connections, opened file, terminal sessions etc…
❖ We choose finally block to do this because finally block will be executed always
irrespective of the exception.
CUSTOM EXCEPTION / USER DEFINED EXCEPTION:
1. Create a custom unchecked exception called InsufficiantbalanceException throw this
exception if any user try’s to withdraw the money more than the balance.
2. Create a custom unchecked exception called NotEligibleForMarriageException throw this
exception when any male or female type to marry before 21 years.
3. Create a custom unchecked exception called NotEligibleForInterviewException throw
this exception when not attended the mock.