CS2312 Lecture 8

Exceptions

An exception or exceptional event is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

The following will cause exceptions:  

  • Accessing an out-of-bounds array element  
  • Writing into a read-only file  
  • Trying to read beyond the end of a file  
  • Sending illegal arguments to a method  
  • Performing illegal arithmetic (e.g divide by 0)  
  • Hardware failures  

When an exception occurs, we say it was thrown or raised

When an exception is dealt with, we say it is handled or caught

The block of code that deals with exceptions is known as an exception handler 

public class ArrayExceptionExamole{
    public static void main(String args[]){
        String[] names = {"xxx","XXX"};
        System.out.println(names[2]);
    }
}

// The println in the above code causes an exception to be thrown with the following exception message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at
ArrayExceptionExample.main(ArrayExceptionExample.j ava:4)

Exception class: java.lang.ArrayIndexOutOfBoundsException

Array index that is out out of bounds: 2

Method throws the exception: ArrayExceptionExample.main

File contains the method:  ArrayExceptionExample.java

Line of the file throws the exception: 4

 

Throwing Exceptions

Use the throw statements to throw an exception

if (student == null)
    throw new NullPointerException();

throw statement requires a single argument: a Throwable object

Throwable objects are instances of any subclass of the Throwable class. 

 

Handling Exceptions

Use a try-catch block to handle exceptions that are thrown

try{
    // code that might throw exception
} catch([Type of Exception] e){
    // what to do if exception is thrown
} catch(ExceptionType<1> e1){
    // what to do if exception is thrown
} catch(ExceptionType<2> e2){
    // what to do if exception is thrown
}catch(ExceptionType<3>e3){
     // what to do if exception is thrown
}

// 1. try {} block may have one or multiple statements.
// 2. try{} block may throw a single type of Exception or multiple exceptions. But at a time it can throw only single type of exception.
// 3. There can be multiple catch() { .. } blocks associated with single try{} block.
// 4. If try{} block can throw multiple exceptions then user should catch all exceptions. (one catch block for each type of exception)

Example:

package exceptions;

class ExceptionDemo
{
    public static void main(String args[])
    {
        int a[]= {5,10};
        try{
            int b= Integer.parseInt(args[0]);
            int x = a[b]/(b-a[1]);
            System.out.println("x="+x);
        }
        catch(ArithmeticException e)
        {
            System.out.println(e.toString());
        }
        catch(NumberFormatException e)
        {
            System.out.println(e.toString());
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e.toString());
        }
        System.out.println("Hello This is Exception Test");
    } // End of main() method
}// End of class Exceptiondemo

Finally Block

Can also use the optional finally block at the end of the try-catch block  

finally block provides a mechanism to clean up regardless of what happens within the try block. (Can be used to close files or to release other system resources)

The final block is always excuted. And the next statement will be excuted too.

 

Exceptions - Checked and Unchecked

Java allows for two types of exceptions:

Checked  

  • If your code invokes a method which is defined to throw checked exception, your code MUST provide a catch handler
  • The compiler generates an error if the appropriate catch handler is not present  
  • Those other exceptions that the compiler can detect easily  
  • Usually originate in library code.  For example, exceptions occurring during I/O, SMSLib, Files  
  • Compiler ensures that: checked exceptions are:  caught using try-catch or  are specified to be passed up to calling method 

  Handling Checked Exception

Every method must catch checked exceptions OR specify that it passes them to the caller (using the throws keyword)

void readFile(String filename) { 
    try {
        FileReader reader = new FileReader("myfile.txt");
        // read from file . . .
    } catch (FileNotFoundException e) {
        System.out.println("file was not found");
    }
}

// OR

void readFile(String filename) throws FileNotFoundException{
    FileReader reader = new FileReader("myfile.txt");
    // read from file . . .
}

Unchecked

  • These exceptions can occur through normal operation of the virtual machine.  You can choose to catch them or not.
  • If an unchecked exception is not caught, it will go to the default catch-all handler for the application
  • All Unchecked exceptions are subclassed from RuntimeException  
  • Unchecked exceptions or RuntimeExceptions occur within the Java runtime system    
  • Examples of unchecked exceptions
    • arithmetic exceptions (dividing by zero)  
    • pointer exceptions (trying to access an object’s members through a null reference)  
    • indexing exceptions (trying to access an array element with an index that is too large or too small)      
  • Can occur at many points in the program  
  • Program handling such exceptions would be cluttered, pointlessly. (Only handle unchecked exceptions at important program points)

  Common Unchecked Exceptions: 

  NullPointerException

          int [] arr = null;
          arr[0] = 1;    // NullPointerException
          arr = new int [4];
          int i;
          for (i = 0; i <= 4; i++)
         {
            arr[i] = i;
            arr[i-1] = arr[i-1] / 0;
         }

  ArrayIndexOutOfBoundsException

int [] arr = null;
arr[0] = 1;
arr = new int [4];
int i;
for (i = 0; i <= 4; i++)
{
  arr[i] = i;     // ArrayIndexOutOfBoundsException
  arr[i-1] = arr[i-1] / 0;
}

  ArithmeticException

 int [] arr = null;
 arr[0] = 1;
 arr = new int [4];
 int i;
 for (i = 0; i <= 4; i++)
 {
   arr[i] = i;
   arr[i-1] = arr[i-1] / 0;   // ArithmeticException
 }

  ArrayIndexOutOfBoundsException OR NumberFormatException

class Exceptiondemo2
{
public static void main(String args[])
{
double a= Double.parseDouble(args[0]); 
}
}
// args[0] can throw either ArrayIndexOutOfBoundsException or NumberFormationException

 

Write Own Exceptions

At lease 2 typre of execption constructors exist:

1. Default construct: No arguments

NullPointerException e = new NullPointerException();

2. Constructor that has a detailed message: Has a single String argument

IllegalArgumentExceptione e = new IllegalArgumentException(“Number must be positive");

 

// Your own exceptions must be a subclass of the Exception class and have at least the two standard constructors

public class MyCheckedException extends IOException{
    public MyCheckedException() {} 
    public MyCheckedException(String m){ super(m);}
}
 
public class MyUncheckedException extends RuntimeException {
    public MyUncheckedException() {} 
    public MyUncheckedException(String m){ super(m);}
}

If a user can reasonably be expected to recover from an exception, make it a checked exception  

If a user cannot do anything to recover from the exception, make it an unchecked exception 

Exception Class Hierarachy

 

Examples and Review

1.

package exceptions;

class ExceptionDemo1
{
    public static void main(String arhs[])
    {
        int a=10;
        int b= 5;
        int c =5;
        try
        {
            int x = a/(b-c);
            System.out.println("c="+c);
        }
        catch(ArithmeticException e)
        {
            System.out.println(e.toString());
        }
        int y = a/(b+c);
        System.out.println("y="+y);
    }
}
java.lang.ArithmeticException: / by zero 
y=1

2.

package exceptions;

class Nestedtry {
    public static void main(String args[]) {
        int a[] = {2,5,6};
        try {
            int b = Integer.parseInt(args[0]);
            try  {
                int c[] = {4,5,6};
                int d  = c[b]/(c[b]-4);
            } // End of inner try
            catch(ArrayIndexOutOfBoundsException e){
                System.out.println("Exception : "+ e.toString());
                System.out.println("By Inner try");
            }
            catch(ArithmeticException e){
                System.out.println("Exception : "+ e.toString());
                System.out.println("By Inner try");
            }
        } // End of outer try
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("Exception : "+e.toString());
            System.out.println("By Outr try");
        }
        catch(NumberFormatException e){
            System.out.println("Exception : "+ e.toString());
            System.out.println("By Outer try");
        }
    } // End of main
} // End of class

D:\java\bin>java nestedtry
Exception : java.lang.ArrayIndexOutOfBoundsException: 0
By Outer try

D:\java\bin>java nestedtry 4
Exception : java.lang.ArrayIndexOutOfBoundsException: 4
By Inner try

D:\java\bin>java nestedtry 0
Exception : java.lang.ArithmeticException: / by zero
By Inner try

3.

 

  

 

posted @ 2018-04-14 18:52  Charonnnnn  阅读(164)  评论(0编辑  收藏  举报