Uploaded by abhishekpatelmrj

Exception Handling

advertisement
Exception Handling
in
JAVA
by
Kumar Saurabh
Asst. Professor
PSIT, Kanpur
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Types of Error
Syntax Error – These error arises due to the rules
of the language which have not been followed,
and detected by the compiler.
2. Run Time Errors – These error arises when the
program is running and the environment detects
an operation that is impossible to carry out.
3. Logical Errors – These error arises when a program
doesn't perform the way it was intended to
achieve its goal
1.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Exception Handling
An Exception is an abnormal condition, in a program it is an
event that disrupts the normal flow of the program.
The exception handling is one of the powerful mechanism
to handle the runtime errors so that normal flow of the
application can be maintained.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Runtime Errors
Considering a scenario:
Suppose in a program there are 8 statements and an exception
arises in statement 4, then rest of the statement i.e. statement
5,6,7 & 8 will not be executed.
Statement1;
Statement2;
Statement3;
Statement4; //exception arises
Statement5;
Statement6;
Statement7;
Statement8;
Statement 5,6,7 & 8
are skipped and the
program is terminated
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Catching Runtime Errors
Considering a scenario:
Suppose in a program there are 8 statements and an exception arises in statement 4, then rest of the
statement i.e. statement 5,6,7 & 8 will not be executed to solve this we need to catch Exception.
Statement1;
Statement2;
Statement3;
try{
Statement4; //exception arises
}
catch(Exception e)
{
Statement n;
}
Statement5;
Statement6;
Only statement 4 is skipped, control
transferred to catch block and
Statement n,5,6,7 & 8 will be
continued
Statement7;
Statement8;
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Exception Classes
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
Several more classes
IllegalArgumentException
LinkageError
VirtualMachineError
Error
AWTError
Several more classes
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Several more classes
System Errors
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little you
can do beyond notifying the user
and trying to terminate the
program gracefully.
LinkageError
VirtualMachineError
Error
AWTError
Several more classes
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Several more classes
Exceptions
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
Several more classes
IllegalArgumentException
LinkageError
VirtualMachineError
Error
AWTError
Several more classes
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Several more classes
Exception Handling Mechanism

try

catch

finally

throw

throws
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Try Catch Block

In a Java Program, the code that might throw an exception must be
enclosed in a try block

Every try block must be followed by either a catch block or a finally
block or both (as required)

It must be used with in a method

In a Java program catch block is used to handle the exception

Multiple catch block can be placed with every try block

Catch block can only be used after the try block only
Example1:
try{
//code that might throw exception
}catch(Exception_class_Name ref_variable){}
Example2:
try{
//code that might throw exception
}finally{}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Internal working of Try Catch Block
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Try Catch Block: Example
public class Exceptn {
public static void main (String args[])
{
int []arr={0,10,12,15,16};
try{
for(int i=0;i<=5;i++)
{
System.out.println("arr["+i+"] is = "+arr[i]);
}
}
catch( Exception es)
{
System.out.println("from catch and exception is: "+ es);
}
System.out.println("Code continues......");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Throws
ArrayIndexOuutOfBou
ndsException
catch block catches the
Exception
Output:
Catching Exceptions : Example
arr[0] is = 0
arr[1] is = 10
public class Exceptn {
arr[2] is = 12
public static void main (String args[])
{
arr[3] is = 15
int []arr={0,10,12,15,16};
arr[4] is = 16
from catch and exception is:
try{
java.lang.ArrayIndexOutOfBounds
for(int i=0;i<=5;i++)
{
Exception: 5
System.out.println("arr["+i+"] is = "+arr[i]); Code continues......
}
}
Exception Arises
catch( Exception es)
{
System.out.println("from catch and exception is: "+ es);
}
System.out.println("Code continues......");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Try block with Multiple catch block
public class MultiCatch {
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("from catch 1");}
catch(ArithmeticException e)
{System.out.println("from catch 2");}
catch(Exception e)
{System.out.println("from catch 3");}
System.out.println("code continues....");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Rule:
At a time only one Exception is occurred
and at a time only one catch block is
executed.
All catch blocks must be ordered from
most specific to most general i.e. catch for
ArrayIndexOutOfBoundsException must
come before catch for Exception , else the
code will generate compile time error
Output:
from catch 2
code continues....
Checked Exception
• Checked exceptions are checked at compile-time, i.e. the
compiler forces the programmer to check and deal with the
exceptions
• Any
classes
that
extend
Throwable
class
except
RuntimeException and Error are known as checked
exceptions e.g. AWTException, SQLException etc.
Unchecked Exception
• Unchecked exceptions are checked at run-time.
• Any classes that extend RuntimeException are known as
unchecked
exceptions
e.g.
NullPointerException,
ArithmeticException, etc.
• RuntimeException, Error and their subclasses are known as
unchecked exceptions
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
CheckedException Demostration
class CheckedException
{
public static void main(String as[])
{
CheckedException e=new CheckedException();
try{
CheckedException ee=e.clone();
}catch(CloneNotSupportedException e1)
{
System.out.println(“CheckedException Occurred “+e1.getMessage());
}
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Example Cases of Unchecked Exception
• String s=null;
System.out.println(s.length());//NullPointerException
• String s=“Hello";
int i=Integer.parseInt(s);//NumberFormatException
• int a=50/0;//ArithmeticException
• int a[]=new int[50];
a[51]=150; //ArrayIndexOutOfBoundsException
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Unchecked Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
Several more classes
IllegalArgumentException
LinkageError
Several more classes
VirtualMachineError
Error
AWTError
Several more classes
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Unchecked exception.
Java Nested try block

The try block within a try block is known as nested try block in
java.
 Why
use nested try block
Sometimes
a situation may arise where a part of a block
may cause one error and the entire block itself may cause
another error.
In
such cases, exception handlers have to be nested
19
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Exception in Method Overriding

If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but can declare
unchecked exception.

If the superclass method declares an exception, subclass overridden
method can declare same, subclass exception or no exception but cannot
declare parent exception.
20
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java Exception propagation(Chaining)

An exception is first thrown from the top of the stack and if it is not caught,
it drops down the call stack to the previous method, If not caught there, the
exception again drops down to the previous method, and so on until they are
caught or until they reach the very bottom of the call stack.

This is called exception propagation.
Rule: By default Unchecked Exceptions are forwarded in calling chain
(propagated).
21
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Program of Exception Propagation
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
22
Throw Keyword

It is a used to explicitly thrown an error.

By using throw keyword we can throw either checked or unchecked exception

throw keyword is mainly used to throw custom exception
public class ThrowKeyword {
static void checkAge(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("You can caste your vote");
Output:
}
Exception in thread "main"
public static void main(String args[]){
java.lang.ArithmeticException: not valid
checkAge(15);
at ThrowKyword.checkAge(ThrowKyword.java:4)
System.out.println(" code continues...");
at ThrowKyword.main(ThrowKyword.java:9)
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
}
Example1:
throw exception;
Example2:
throw new IOException(“sorry IO error”);
Throws Keyword

It is a used to declare an exception.

It is an information about the exception that may occur in the
code, so that code for handling the exception and maintaining the
normal flow of execution of the program must be provided
returntype method_name() throws exceptionclassname{
//method code
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Throws Keyword
import java.io.IOException;
public class ThrowsKyword {
void t1()throws IOException{
throw new IOException("I/O error");//checked exception
}
void t2()throws IOException{
Output:
t1();
from catch...java.io.IOException: I/O error
}
code continues...
void t3(){
try{
t2();
}catch(Exception e){System.out.println("from catch...“+e);}
}
public static void main(String args[]){
ThrowsKyword obj=new ThrowsKyword ();
obj.t3();
System.out.println("code continues...");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Difference between throw and throws in Java
No.
throw
throws
1)
Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to declare
an exception.
2)
Checked exception cannot be
propagated using throw only.
Checked exception can be propagated
with throws.
3)
Throw is followed by an instance.
Throws is followed by class.
4)
Throw is used within the method.
Throws is used with the method
signature.
5)
You cannot throw multiple
exceptions.
You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
26
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Finally Block

It is a block which is used to execute that important code which must
be executed.

Whether the exception occurs or not or exception is handled or not,
Finally block is always executed.

Finally Block must be followed by try or catch block

A program code can have either a catch or a finally or both for each
try block

A program can have 0 or more catch block for each try block but can
have only one finally block.

If you don't handle exception, before terminating the program, JVM
executes finally block(if any).

The finally block will not be executed if program exits, either by
calling System.exit() or by such error which aborts the program
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Execution of Finally Block
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Try block with Multiple catch and finally block
public class MultiCatch {
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("from catch 1");}
catch(ArithmeticException e)
{System.out.println("from catch 2");}
catch(Exception e)
{System.out.println("from catch 3");}
finally
{System.out.println("from finally");}
System.out.println("code continues....");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Output:
from catch 2
from finally
code continues....
Custom Exception
User defined exceptions in java are also known as Custom exceptions. Most of the times when we
are developing an application in java, we often feel a need to create and throw our own
exceptions. These exceptions are known as User defined or Custom exceptions.
Example :Class AgeNotSupportedException extends Exception
{
AgeNotSupportedException(){ super(); }
AgeNotSupportedException(String msg){ super(msg); }
}
Raise Custom Exception :throw new AgeNotSupportedException(); or
throw new AgeNotSupportedException(“Age Not Valid”);
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
QnA
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q1) What is an Exception?
Ans) The exception is said to be thrown whenever an exceptional event occurs in java
which signals that something is not correct with the code written and may give unexpected
result. An exceptional event is a occurrence of condition which alters the normal program
flow. Exceptional handler is the code that does something about the exception.
Q2) Exceptions are defined in which java package?
Ans) All the exceptions are subclasses of java.lang.Exception.
Q3) How are the exceptions handled in java?
Ans) When an exception occurs the execution of the program is transferred to an
appropriate exception handler. The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a
guarded region.
The catch clause matches a specific exception to a block of code which handles that
exception.
And the clean up code which needs to be executed no matter the exception occurs or not is
put inside the finally block
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q4) Explain the exception hierarchy in java
Ans) The hierarchy is as follows.
Throwable is a parent class of all Exception classes. There are two types of Exceptions:Checked
exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends
Exception class.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q5) What is Runtime Exception or unchecked exception?
Ans) Runtime exceptions represent problems that are the result of a programming
problem. Such problems include arithmetic exceptions, such as dividing by zero;
pointer exceptions: such as trying to access an object through a null reference;
and indexing exceptions: such as attempting to access an array element through
an index that is too large or too small.
Runtime exceptions need not be explicitly caught in try catch block as it can
occur anywhere in a program, and in a typical one they can be very numerous.
Having to add runtime exceptions in every method declaration would reduce a
program's clarity. Thus, the compiler does not require that you catch or specify
runtime exceptions (although you can). The solution to rectify is to correct the
programming logic where the exception has occurred or provide a check.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q6) What is difference between Error and Exception?
Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory
error. These JVM errors you can not repair them at runtime.Though error can be caught in
catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input or human error etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases
it is possible to recover from an exception (probably by giving user a feedback for
entering proper values etc.)
Q7) What is checked exception?
Ans) Checked exception are the exceptions which forces the programmer to catch
them explicitly in try-catch block. It is a subClass of Exception. Example:
IOException.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q8) What is throw keyword?
Ans) Throw keyword is used to throw the exception manually. It is mainly used
when the program fails to satisfy the given condition and it wants to warn the
application.The exception thrown should be subclass of Throwable
public void parent(){
try{
child();
}catch(MyCustomException e){
}
}
public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using throw keyword");
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q9) What is throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the
calling method to handle it by simply putting the throws clause at the function
declaration.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}
public void child throws MyCustomException{
//put some logic so that the exception occurs.
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q10) What are the possible combination to write try, catch finally block?
Ans
1 try{
//lines of code that may throw an exception
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}
2 try{}finally{}
3 try{
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}
The catch blocks must always follow the try block. If there are more than one catch
blocks they all must follow each other without any block in between. The finally block
must follow the catch block if one is present or if the catch block is absent the finally
block must follow the try block.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q11) How to create custom Exception?
Ans) To create you own exception extend the Exception class or any of its
subclasses.
• class New1Exception extends Exception { } // this will create Checked Exception
• class NewException extends IOExcpetion { } // this will create Checked exception
• class NewException extends NullPointerExcpetion { } // this will create UnChecked
exception
Q12) When to make a custom checked Exception or custom unchecked Exception?
Ans) If an application can reasonably be expected to recover from an exception,
make it a checked exception. If an application do want to do anything to recover
from the exception, make it an unchecked exception. For e.g in client server
model, if server is not able to talk with DB or some IO operation went wrong, its
ok to throw the unchecked exception so that container can handle it and throw
appropriate error response.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q13) What is StackOverflowError?
Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System
when it Encounters that your application/code has ran out of the memory. It may
occur in case of recursive methods or a large amount of data is fetched from the
server and stored in some object. This error is generated by JVM
Q14) Why did the designers decide to force a method to specify all uncaught
checked exceptions that can be thrown within its scope
Ans) Any Exception that can be thrown by a method is part of the method's public
programming interface. Those who call a method must know about the exceptions
that a method can throw so that they can decide what to do about them. These
exceptions are as much a part of that method's programming interface as its
parameters and return value.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Q15) What is exception matching??
Ans) Exception matching is the process by which the the jvm finds out the
matching catch block for the exception thrown from the list of catch blocks.
When an exception is thrown, Java will try to find by looking at the available
catch clauses in the top down manner. If it doesn't find one, it will search for a
handler for a supertype of the exception. If it does not find a catch clause that
matches a supertype for the exception, then the exception is propagated down
the call stack. This process is called exception matching.
Q16) Can a catch block throw the exception caught by itself?
Ans) Yes. This is called rethrowing of the exception by catch block.
e.g. the catch block below catches the FileNotFoundException and re throws it
again.
void checkEx() throws FileNotFoundException {
try{ //code that may throw the FileNotFoundException
}catch(FileNotFoundException eFnf){
Throw new FileNotFoundException();
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
}
Q17) What happens…?
try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
Compilation fails. The catch block for handling the most specific exceptions must
always be placed above the catch block written to handle the more general exceptions.
Q18) Does the order of the catch blocks matter if the Exceptions caught by
them are not subtype or super type of each other?
Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If
one Exception class is not a subtype or supertype of the other, then the order
in which their handlers(catch clauses) are placed does not matter.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Related documents
Download