Exception Handling: Submitted by K.Radhakrishnan Iii Year Cse Programming Paradigms
Exception Handling: Submitted by K.Radhakrishnan Iii Year Cse Programming Paradigms
Submitted By
K.RADHAKRISHNAN
III YEAR CSE
PROGRAMMING PARADIGMS
ExceptionHandling
o Similarly,whenwewriteprogramsaspartofanapplication,wemay
havetovisualizethechallengesthat candisruptthenormalflowof executionofthecode.
o Oncewe knowwhatarethedifferentsituationsthatcandisruptthe flow ofexecution,
wecantakepreventivemeasurestoovercomethese disruptions.
o Injava,thismechanismcomesin theformofExceptionHandling.
What is anException?
Inprocedural programming,itisthe responsibilityofthe programmerto ensurethattheprogramsare
error- freein allaspects
Errors have to be checked and handled manuallyby usingsome errorcodes
Butthiskindofprogrammingwas very cumbersome and led to spaghetticode.
Java provides an excellent mechanism forhandlingruntime errors.
An exception is an event that occurs during
theexecutionofaprogramthatdisruptsthenormalflowofinstructions.
Theabilityofaprogramtointerceptrun-timeerrors, take corrective measures and continue
execution is referred toasexceptionhandling.
o Therearevarioussituationswhenanexceptioncouldoccur:
Attemptingtoaccessafilethatdoesnotexist
Insertinganelementintoanarrayatapositionthatis bounds
notinits
Performingsomemathematicaloperationthatisnotpermitted
Declaringanarrayusingnegativevalues.
Exception Type:
Uncaught Exceptions
class Demo {
public static void main(String args[]) {
int x = 0;
int y = 50/x;
System.out.println(y = +y);
}
}
Although this program will compile, but when you execute it, the Java
run-time-system will generate an exception and displays the following
output on the console :
java.lang.ArithmeticException: / by zero
at Demo.main(Demo.java:4)
Exception Types
There are several built-in exception classes that are used to
handle the very fundamental errors that may occur in your
programs
You can create your own exceptions also by extending the Exception class
These are called user-defined exceptions, and will be used in situations that are unique to your
applications.
Handling Runtime Exceptions
Whenever an exception occurs in a program, an object representing
that exception is created and thrown in the method in which the exception occurred
Either you can handle the exception, or ignore it
In the latter case, the exception is handled by the Java run-time-system
and the program terminates
However, handling the exceptions will allow you to fix it, and prevent the
program from terminating abnormally.
Exception Handling Keywords
Javas exception handling is managed using the following
keywords: try, catch, throw, throws and finally.
try {
// code comes here
}
catch(TypeofException obj) {
//handle the exception
}
finally {
//code to be executed before the program ends
}
Exception Handling Keywords(Contd.).
Any part of the code that can generate an error should be put in the try block
Any error should be handled in the catch block defined by the catch clause
This block is also called the catchblock, or the exception handler
The corrective action to handle the exception should be put in the catch block.
How to Handle exceptions
class ExceptDemo{
public static void main(String args[]){
int x, a;
try{
x = 0;
a = 22 / x;
System.out.println("This will be bypassed.");
}
catch (ArithmeticException e){
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Multiple Catch Statements
A single block of code can raise more than one exception
You can specify two or more catch clauses, each catching a different type of execution
When an exception is thrown, each catch statement is inspected in order, and the first one whose type
matches that of the exception is executed
After one catch statement executes, the others are bypassed, and execution continues after the
try/catchblock.
Example:
class MultiCatch{
public static void main(String args[]){
try{
int l = args.length;
System.out.println("l = " +l);
int b = 42 / l;
int arr[] = { 1 };
arr[22] = 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
blocks.");
}
}
Multiple Catch Statements involving Exception Superclasses & Subclasses
When you use multiple catch statements, it is important to remember that exception subclasses must
come before any of their exception superclasses
This is because a catch statement that uses a superclass will catch exceptions of that type as well as
exceptions of its subclasses
Thus, a subclass exception would never be reached if it came after its superclass that manifests as an
unreachable code error.
Nested try Statements
The try statement can be nested
If an inner try statement does not have a catch handler for a particular exception, the outer blocks
catch handler will handle theexception
This continues until one of the catch statement succeeds, or until all of the nested try statements are
exhausted
If no catch statement matches, then the Java runtime system will handle the exception
Using throw
System-generated exceptions are thrown automatically
At times you may want to throw the exceptions explicitly which can
be done using the throw keyword
The exception-handler is also in the same block
The general form of throw is:
throw ThrowableInstance
Here, ThrowableInstance must be an object of type Throwable, or a subclass of Throwable
class ThrowDemo{
public static void main(String args[]) {
try {
int age=Integer.parseInt(args[0]);
if(age < 18)
throw new ArithmeticException();
else
if(age >=60)
throw new ArithmeticException("Employee is
retired");
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("After Catch");
}
}
Using throws
Sometimes, a method is capable of causing an exception that it does not handle
Then, it must specify this behavior so that callers of the method can guard themselves against that
exception
While declaring such methods, you have to specify what type of exception it may throw by using the
throws keyword
A throws clause specifies a comma-separated list of exception types that a method might throw:
type method-name( parameter list) throws exception-list
Implementing throws
import java.io.*;
class ThrowsDemo{
static void throwOne() throws
FileNotFoundException{
System.out.println("Inside throwOne.");
throw new FileNotFoundException();
}
public static void main(String args[]) {
try{
throwOne();
}
catch (FileNotFoundException e){
System.out.println("Caught " + e);
}
}
}
Using finally
When an exception occurs, the execution of the program takes a non-linear path, and could bypass
certain statements
A program establishes a connection with a database, and
an exception occurs
The program terminates, but the connection is still open
To close the connection, finally block should be used
The finally block is guaranteed to execute in all
circumstances
Using finally (Contd.).
import java.io.*;
class FinallyDemo{
static void funcA() throws
FileNotFoundException{
try{
System.out.println("inside funcA(
)");
throw new FileNotFoundException( );
}
finally{
System.out.println("inside finally
of funA( )");
}
}
static void funcB(){
try{
System.out.println("inside funcB(
)");
}
finally{
System.out.println("inside finally
of funB( )");
}
}
static void funcC() {
try{
System.out.println("inside funcC(
)");
}
finally{
System.out.println("inside finally
of funcC( )");
}
}
public static void main(String args[]){
try{
funcA();
}
catch (Exception e){
System.out.println("Exception
caught");
}
funcB( );
funcC( );
}
} catch (Exception e){
System.out.println("Exception
caught");
}
funcB( );
funcC( );
}
}