Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

CHAPTER 4 :

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?

• An Exception is an unwanted event that interrupts the normal flow of the


program.

• When an exception occurs program execution gets terminated. In such cases we


get a system generated error message.

• 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)

All exceptions should fit in one of these categories

• programming logic errors

• 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.

• programming logic errors


Error exceptions occur when a program determines that it has achieved a
state which should not be possible, such as accessing the tenth element of a
five element array or attempting to pop an element from an empty stack
Different between error and exception
Errors indicate that something severe enough has gone wrong, the application
should crash rather than try to handle the error. Errors terminate the program for
sure and they cannot be handled in any way. Eg: Stack overflow

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:

NullPointerException – When you try to use a reference that points to null.

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.

ArrayIndexOutOfBoundsException – When you try to access the elements of an


array out of its bounds, for example array size is 5 (which means it has five
elements) and you are trying to access the 10th element.
Error Types – Non-Fatal Errors

A non-fatal error means something bad happened, but we could


recover and continue.  

• 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.

Fatal error - cause programs to terminate immediately without having


successfully performed 

• 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.

• A try block must be followed by catch blocks or finally block or both.

Syntax:

try{ //statements that may cause an


exception }
Try-catch block – and rules(2)
• A catch block is where you handle the exceptions.

• 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 try-with-resources statement is a try statement that declares one or more


resources.

• The try-with-resources statement ensures that each resource is closed at the


end of the statement.

• Any object that implements java.lang.AutoCloseable, which includes all objects


which implement java.io.Closeable, can be used as a resource.
Finaly block- try-with-resources statements (2)

static. String readFirstLineFromFile(String path) throws IOException {


try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine(); } }

• The following example reads the first line from a file. It uses an instance
of BufferedReader to read data from the file. 

• BufferedReader is a resource that must be closed after the program is finished


with it

• Because the BufferedReader instance is declared in a try-with-resource


statement, it will be closed regardless of whether the try statement completes
normally or abruptly (as a result of the
method BufferedReader.readLine throwing an IOException).
Finaly block- try-with-resources statements (3)

Prior to Java SE 7, you can use a finally block to ensure that a resource


is closed
. regardless of whether the try statement completes normally or
abruptly.

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {


BufferedReader br = new BufferedReader(new FileReader(path));
try { return br.readLine();
}
finally { if (br != null) br.close();
}
}
Checked exceptions
• All exceptions other than Runtime Exceptions are known as
Checked exceptions as the compiler checks them during
compilation to see whether the programmer has handled them or
not.
• Checked exception (compile time) force you to handle them, if
you don’t handle them then the program will not compile.
• If these exceptions are not handled/declared in the program, you
will get compilation error. For example, SQLException,
IOException, ClassNotFoundException etc.
• Throws keyword is used for handling checked exceptions. By
using throws we can declare multiple exceptions in one go.
Checked exceptions cont.
import java.io.*;
class Example {
public static void main(String args[])
{ FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked exception
*/
The program causes compile time errors,
fis = new FileInputStream("B:/myfile.txt");
Three exceptions are not handled. Will get t he
int k;
error below.
 
/* Method read() of FileInputStream class also throws
Output:
* a checked exception: IOException */
while(( k = fis.read() ) != -1) Exception in thread "main" java.lang.Error: Unresolved
compilation problems:
{ System.out.print((char)k); Unhandled exception type FileNotFoundException
} Unhandled exception type IOException
  Unhandled exception type IOException
/*The method close() closes the file input stream
* It throws IOException*/
fis.close();
}
}
Checked exceptions cont.
Two ways to handle checked exceptionerror :
1: Declare the exception using throws keyword. 2: Handle them using try-catch blocks.
import java.io.*;
import java.io.*; class Example {
class Example { public static void main(String args[])
public static void main(String args[]) throws IOException {
{ FileInputStream fis = null;
FileInputStream fis = null; try{
fis = new FileInputStream("B:/myfile.txt"); fis = new FileInputStream("B:/myfile.txt");
}catch(FileNotFoundException fnfe){
int k;
System.out.println("The specified file is not " +
"present at the given path");
while(( k = fis.read() ) != -1) }
{ catch(IOException ioe){
System.out.print((char)k); System.out.println("I/O error occurred: "+ioe);
} }
fis.close(); fis.close();
}
}
} }
Output: Output:
File content is displayed on the screen. This code will run fine and will display the file content.
Checked exceptions cont.
Other Checked Exceptions

•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.

public void myMethod() throws ArithmeticException, NullPointerException{


// Statements that might throw an exception
}
public void myMethod1() throws ArithmeticException {
// Statements that might throw an exception
}

public static void main(String args[]) {


try {
myMethod();

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

• Runtime Exceptions are also known as Unchecked Exceptions.


These exceptions are not checked at compile-time so compiler
does not check whether the programmer has handled them or not
but it’s the responsibility of the programmer to handle these
exceptions and provide a safe exit.

• example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException etc
User defined 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.

•  User-defined exception must extend Exception class.

• The exception is thrown using throw keyword.

• Syntax of throw keyword:

throw new exception_class("error message");

• Eg:

throw new ArithmeticException("dividing a number by 5 is not allowed in this program");


User defined Exceptions (example(1)

/* This is my Exception class, I have named it class Example1{


MyException public static void main(String args[]){
* you can give any name, just remember that it should try{
* extend Exception class System.out.println("Starting of try block");
*/ // I'm throwing the custom exception using throw
class MyException extends Exception{ throw new MyException("This is My error Message");
String str1; }
/* Constructor of custom exception class catch(MyException exp){
* here I am copying the message that we are passing System.out.println("Catch Block") ;
while System.out.println(exp) ;
* throwing the exception to a string and then displaying }
* that string along with the message. }
*/ }
MyException(String str2) {
str1=str2;
}
public String toString(){ Output
return ("MyException Occurred: "+str1) ; Starting of try block
} Catch Block
}
MyException Occurred: This is My error Message
User defined Exceptions (example(2)
public class Example2
class InvalidProductException extends {
Exception void productCheck(int weight) throws InvalidProductException{
{ if(weight<100){
public InvalidProductException(String s) throw new InvalidProductException("Product Invalid");
{ }
// Call constructor of parent Exception }
super(s); public static void main(String args[])
} {
} Example2 obj = new Example2();
try
{
obj.productCheck(60);
}
catch (InvalidProductException ex)
{
Output: System.out.println("Caught the exception");
Caught the exception System.out.println(ex.getMessage());
Product Invalid }
}
}
Rethrowing Exceptions (1)

• 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)

public class RethrowException {


public static void test1() throws Exception {
System.out.println("The Exception in test1() method");
throw new Exception("thrown from test1() method");
}
public static void test2() throws Throwable {
try {
test1();
} catch(Exception e) {
System.out.println("Inside test2() method");
throw e;
}
}
public static void main(String[] args) throws Throwable {
try {
test2();
} catch(Exception e) { Output
System.out.println("Caught in main"); The Exception in test1() method
} Inside test2() method
} Caught in main
Throws and Throw

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.

You might also like