Professional Documents
Culture Documents
Chapter 4 - EXCEPTION HANDLING - swc3133 Final
Chapter 4 - EXCEPTION HANDLING - swc3133 Final
EXCEPTION
HANDLING
ADVANCED OBJECT–ORIENTED PROGRAMMING
WHAT IS EXCEPTION HANDLING
■ one of the powerful mechanism to handle the runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc. so that
normal flow of the application can be maintained.
statement 1;
statement 2; Suppose there are 10 statements in your program
statement 3; and there occurs an exception at statement 5, the rest
of the code will not be executed i.e. statement 6 to
statement 4;
10 will not be executed. If we perform exception
statement 5 ;//exception handling, the rest of the statement will be executed.
occurs That is why we use exception handling in Java.
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Hierarchy of Exception?
Unchecked
Checked
Unchecked
What is an exception?
• The good thing about exceptions is that they can be handled in Java. By handling
the exceptions we can provide a meaningful message to the user about the issue
rather than a system generated message, which may not be understandable to a
user.
Classification Exceptions (1)
• resource failures
• user errors
Classification Exceptions(2)
• User Error
occurs when a user attempts to do something that is not supported by the system and not
directly prevented by the user interface.
• Resource failure
exceptions occur when some resource outside of the control of the program
(such as memory, disk space, or a peripheral) is not available when needed.
Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions. They are caught either at
compile time or at runtime. Few examples:
ArithmeticException – When bad data is provided by user, for example, when you
try to divide a number by zero this exception occurs because dividing a number
by zero is undefined.
• Flat tires are non-fatal errors. You can’t drive until you fix it, but you
can put on the spare and continue until you patch or replace the tire.
• Your car is wrecked, the other car is wrecked, and neither will drive
again. And, quite possibly, one or more occupants of the vehicles were
killed. Clearly, fatal.
Try-catch block – and rules(1)
• The try block contains set of statements where an exception can occur.
• While writing a program, if you think that certain statements in a program can
throw an exception, enclosed them in try block and handle that exception
• A try block is always followed by a catch block, which handles the exception
that occurs in associated try block.
Syntax:
• This block must follow the try block. A single try block can have several
catch blocks associated with it.
• You can catch different exceptions in try block, the corresponding catch block
that handles that particular exception executes.
• If no exception occurs in try block then the catch blocks are completely
ignored. different catch blocks. When an exception occurs
try {
//statements that may cause an exception
}
catch (exception(type) e(object)) {
//error handling code
}
Example1
class Example1 {
OUTPUT
public static void main(String args[]) {
int num1, num2; You should not divide a number by zero
I'm out of try-catch block in Java
try {
/* We suspect that this block of statement can throw exception so we handled it
* by placing these statements inside try and handled the exception in catch block */
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception occurs in try block */
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks. */
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Example2
class Example2{
public static void main(String args[]){
try{ OUTPUT
int a[]=new int[7]; Warning: ArithmeticException
a[4]=30/0; Out of try-catch block...
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Generic Catch block
• A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or
NullPointerException or any other type of exception, this handles all of them.
catch(Exception e){
//This catch block catches all the exceptions
}
• why we need other catch handlers when we have a generic that can handle all?
This is because in generic exception handler you can display a message
but you are not sure for which type of exception it may trigger so it will
display the same message for all the exceptions
• if catch block ( catch(Exception e)) is put at the first place, just after try block
then in case of any exception this block will execute as it can handle
all exceptions. This catch block should be placed at the last to avoid such
situations.
Combining Exception Handlers
• We have learnt to handle multiple exceptions in our code by providing multiple
numbers of catch block specific to a particular exception.
• We can combine several exceptions in a single catch block. Let’s learn this new
feature. (works only on Java SE 7 and above)
Multiple Exception Combine Exception
try { try {
// Say some file parser code here... // Say some file parser code here...
} }
catch (IOException ex) { catch (IOException ex | ParseException ex |
// log and rethrow exception ClassNotFoundException ex) {
} catch (ParseException ex) { // log and rethrow exception
// log and rethrow exception
}
} catch (ClassNotFoundException ex) {
// log and rethrow exception all those exception handlers that have common code are
combined by using a logical OR operator between their
} exception types. This makes the code simpler.
How Runtime Matches catch Blocks
Whenever an exception occurs in running code, the search for the first matching catch
block begins and the rules listed here are followed:
• A thrown exception object is caught by the catch block that specifies the class of the
occurred exception or its superclass.
• In the case of multiple catch blocks, these are evaluated sequentially in the order
they are specified by applying the first rule. If a catch block is found, the rest of the
catch blocks are ignored.
• A certain catch block will never be executed if a catch block containing its
superclass is listed prior to it. In such situations, a compile-time error is generated.
• The compiler forces the programmer to handle all checked exceptions. In other
words, we must provide error handling for all exceptions except for the
RuntimeException and its subclasses.
• If the try block never throws an exception specified in the catch list, the compiler
generates an error.
Finally block and rules
•. A finally block contains all the crucial statements that must be executed whether
exception occurs or not.
• It must be associated with a try block. finally can not be used without a try
block. Those statements in this block must be executed always.
• A finally block will always be executed after the execution of try block.
Finaly block (Example)
class Example
{ .
Output
public static void main(String args[]) {
try{
Number should not be divided by zero
int num=121/10;
This is finally block
System.out.println(num);
Out of try-catch-finally
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Finaly block- try-with-resources statements(1)
• The following example reads the first line from a file. It uses an instance
of BufferedReader to read data from the file.
•SQLException
•IOException
•ClassNotFoundException
•InvocationTargetException
What is the need of having throws keyword when
you can handle exception using try-catch?(1)
• The throws does the same thing that try-catch does but there are some cases where you would
prefer throws over try-catch.
• Lets say we have a method myMethod() that has statements that can throw either
ArithmeticException or NullPointerException, in this case you can use try-catch as shown
below:
public void myMethod() • But suppose you have several such methods that
{ can cause exceptions, in that case it would be
try { tedious to write these try-catch for each method.
// Statements that might throw an exception The code will become unnecessary long and will
} be less-readable.
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
What is the need of having throws keyword when you can
handle exception using try-catch?(2)
• One way to overcome this problem is by using throws like:
declare the exceptions in the method signature using throws and handle the exceptions where you
are calling this method by using try-catch.
• Another advantage of using this approach is that all the exceptions that are
declared using throws, must be handled when you are calling this method else you
will get compilation error.
myMothod1();
}
throws construct (example1)
import java.io.*;
class ThrowExample {
void myMethod(int num) throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
} the method myMethod() is throwing
two checked exceptions so we have
public class Example1{ declared these exceptions in the method
public static void main(String args[]){ signature using throws Keyword. If we
try{ do not declare these exceptions then the
ThrowExample obj=new ThrowExample(); program will throw a compilation error.
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
} Output:
} java.io.IOException: IOException Occurred
}
Unchecked exceptions
• we can create our own exception class and throw that exception using throw keyword. These
exceptions are known as user-defined or custom exceptions.
• Eg:
• If a catch block cannot handle the particular exception it has caught, we can
rethrow the exception. The rethrow expression causes the originally thrown object
to be rethrown.
• catch block is catching Exception but it’s not part of throws clause. Java 7
compiler analyze the complete try block to check what types of exceptions
are thrown and then rethrown from the catch block.
Syntax
catch(Exception e) {
System.out.println("An exception was
thrown");
throw e;
}
Rethrowing Exceptions (2)
Throws Throw
1. is used to declare an exception. It works similar to the 1. is used to throw an exception explicitly
try-catch block. 2. Syntax wise: throw is followed by an instance of
2. Syntax wise: throws is followed by exception class Exception class
names Eg: throw new ArithmeticException("Arithmetic
eg: throws ArithmeticException; Exception");
3. throws is used in method signature to declare the 3. Throw keyword is used in the method body to throw an
exceptions that can occur in the statements present in exception
the method. Eg:
Eg: void myMethod() {
... try { //throwing arithmetic exception //using throw
//Declaring arithmetic exception //using throws throw new ArithmeticException("Something went
void sample() throws ArithmeticException{ wrong!!");
//Statements }
catch (Exception exp) { System.out.println("Error:
} "+exp.getMessage());
... }
}
4. can handle multiple exceptions by declaring them 4. throw one exception at a time
using throws keyword.