Object Oriented Programming: Exception Handling in Java

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

MCS

Object Oriented Programming

Lecture 12
Exception Handling in Java
MCS
Exception Handling in Java
• The exception handling in java is one of the
powerful mechanism to handle the runtime errors
so that normal flow of the application can be
maintained
• What is exception?
– Dictionary Meaning: Exception is an abnormal
condition.
– In java, exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at
runtime.
• What is exception handling?
– Exception Handling is a mechanism to handle runtime
errors such as ClassNotFound, IO, SQL, Remote etc.
Advantages of using Exception Handling
MCS
• The core advantage of exception handling is to maintain the normal flow
of the application. Exception normally disrupts the normal flow of the
application that is why we use exception handling. Let's take a scenario:
1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5; //exception occurs  
6. statement 6;  
7. statement 7;  
• Suppose there are 7 statements in your program and there occurs an
exception at statement 5, rest of the code will not be executed i.e.
statement 6 to 7 will not run.
• If we perform exception handling, rest of the code will be executed. That
is why we use exception handling in java.
MCS
What is an Exception?
• Exceptional event
• Error that occurs during runtime
• Cause normal program flow to be disrupted
• Examples
– Divide by zero errors
– Accessing the elements of an array beyond its range
– Hard disk crash
– Opening a non-existent file
– Heap memory exhausted
– A user has entered invalid data.
– A file that needs to be opened cannot be found.
– A network connection has been lost in the middle of communications or
the JVM has run out of memory.
MCS
Exceptions

• An exception in Java is an object that is created when an abnormal


situation arises in your program
• This object has members that stores information about the nature of the
problem
• An Exception is always an object of some subclass of the standard class
Throwable
• Java provides a very well defined hierarchy of Exceptions to deal with
situations which are unusual.
• All standard exceptions are covered by two direct subclasses of the class
Throwable
– Class Error
– Class Exception
MCS
The Error and Exception Classes
MCS

• Error class
– Used by the Java run-time system to handle errors occurring in
the run-time environment
– Generally beyond the control of user programs
– Examples
• Out of memory errors
• Hard disk crash

• Exception class
– Conditions that user programs can reasonably deal with
– Usually the result of some flaws in the user program code
– Examples
• Division by zero error
• Array out-of-bounds error
MCS
Types of Exception
• There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says there
are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
• Checked Exception
– The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.
• Unchecked Exception
– The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
• Error
– Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
MCS
Checked Exceptions
• A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer.
• For example, if a file is to be opened, but the file cannot be found, an
exception occurs.
• These exceptions cannot simply be ignored at the time of compilation.
• It means if a method is throwing a checked exception then it should
handle the exception using try-catch block or it should declare the
exception using throws keyword, otherwise the program will give a
compilation error.
• Here are the few other checked exceptions
– SQLException
– IOException
– DataAccessException
– ClassNotFoundException
– InvocationTargetException
MCS
Unchecked Exceptions
• In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable.
• For example,
– A NullPointerException is thrown if you access an object through a
reference variable before an object is assigned to it;
– An IndexOutOfBoundsException is thrown if you access an element
in an array outside the bounds of the array.
• These are the logic errors that should be corrected in the
program.
• Unchecked exceptions can occur anywhere in the program.
• To avoid cumbersome overuse of try-catch blocks, Java does
not mandate you to write code to catch unchecked exceptions.
• Note: All Unchecked exceptions are direct sub classes of
RuntimeException class.
MCS
Common Exception Scenarios
• Scenario where ArithmeticException occurs
– If we divide any number by zero, there occurs an
ArithmeticException.
int a = 50 / 0; // ArithmeticException

• Scenario where NullPointerException occurs


– If we have null value in any variable, performing any
operation by the variable occurs an
NullPointerException.
String s = null;  
// NullPointerException
System.out.println(s.length());
MCS
Common Exception Scenarios
• Scenario where NumberFormatException occurs
– The wrong formatting of any value, may occur
NumberFormatException. Suppose I have a string variable that
have characters, converting this variable into digit will occur
NumberFormatException.
String s = "abc";  
int i = Integer.parseInt(s);//NumberFormatException  

• Scenario where ArrayIndexOutOfBoundsException occurs


– If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below.
int[] a = new int[5];  
a[10] = 50;  // ArrayIndexOutOfBoundsException
MCS
Exception Handling Keywords
• There are 5 keywords used in java
exception handling:
1. try
2. catch
3. finally
4. throw
5. throws
What Happens When an Exception occurs?
MCS

• When an exception occurs within a method,


the method creates an exception object and
hands it off to the runtime system
– Creating an exception object and handing it to
the runtime system is called “throwing an
exception”
– Exception object contains information about
the error, including its type and the state of
the program when the error occurred
MCS
Dealing With Exceptions

• For all subclasses of Exception Class (except


RuntimeException) you must include code to deal
with them
• If your program has the potential to generate an
exception of such a type, you have got two choices
– Handle the exception within the method
– Register that your method may throw such an exception
(You are passing the exception on)
• If you do neither your code won’t compile
MCS
The try-catch Statements
Syntax:
try {
<code to be monitored for exceptions>
} catch (<ExceptionType1> <ObjName>) {
<handler if ExceptionType1 occurs>…
} catch (<ExceptionTypeN> <ObjName>) {
<handler if ExceptionTypeN occurs>…
}
MCS
Example-1
class DivByZero {
public static void main(String[] args) {
try {
System.out.println(3 / 0);
System.out.println("Please print me.");
} catch (ArithmeticException exc) {
// Division by zero is an
// ArithmeticException
System.out.println(exc);
}
System.out.println("After exception.");
Reason of error, can be accessed
} by using exc.getMessage()
}
O/P
java.lang.ArithmeticException: / by zero
Type of error
After exception.
MCS
MCS
Example-2
class MultipleCatch {
public static void main(String[] args) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println("Divisor was 0.");
} catch (ArrayIndexOutOfBoundsException exc2){
System.out.println("Missing argument.");
}
System.out.println("After exception.");
}
} Rule: At a time only one Exception is occurred
and at a time only one catch block is executed.
Example 3
public class TestMultipleCatchBlock {  
MCS
public static void main(String[] args) {
try {
int a[] = new int[5];  
a[5] = 30 / 0;
} catch(ArithmeticException e) {
System.out.println("Arithmetic Exception :" + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println(e.getMessage());
}
System.out.println("rest of the code...");
} Rule: All catch blocks must be ordered from most specific to most general
} i.e. catch for ArithmeticException must come before catch for Exception.

O/P : Arithmetic Exception : java.lang.ArithmeticException: / by zero


rest of the code...
Nested Try
public class NestedTryBlock{         //inner try block 2  
MCS
 public static void main(String args[])     try{    
{        int a[]=new int[5];    
 //outer try block        //assigning the value out of array bounds  
  try{          a[5]=4;    
  //inner try block 1        } 
    try{      //catch block of inner try block 2  
     System.out.println("going to divide      catch(ArrayIndexOutOfBoundsException e)
by 0");              {  System.out.println(e);   }      
int b =39/0;         System.out.println("other statement");    
    }     }  
    //catch block of inner try block 1     //catch block of outer try block  
    catch(ArithmeticException e)     catch(Exception e)  
    {     {  System.out.println("handled the exception (
      System.out.println(e);   outer catch)");  
    }       }    
  System.out.println("normal flow..");    
 }    

You might also like