Review (from CS 170):   exception handling

  • Error reporting in Java is by "throwing" exceptions

  • How to handle exceptions in Java

       try
       {
           // block of code that may throw exception
       }
       catch (Exception e)
       {
           // block of code that deal with exception
       }

  • Unhandled exceptions will cause the Java program to terminate

  • Why do we discuss exception here ?

    • Java has an exception hierarchy that is similar to the class hierarchy

Exception handling example

  • Example Java program that throws the ArrayIndexOutOfBoundsException exception:

        public static void main(String[] args)
        {
            int[] a = new int[10];
    
            try
            {
                a[99] = 1;  // Index out of range
            }
            catch (ArrayIndexOutOfBoundsException e)
            {
    	    System.out.println(e);
            }
        }

DEMO: 04-inheritance/25-exception/Demo.java

The inheritance hierarchy of exceptions

  • The exception types in Java is also organized as an inheritance hierarchy (just like classes)   --   the root is Ecception

      ArrayIndexOutOfBoundsException is-a IndexOutOfBoundsException
      IndexOutOfBoundsException      is-a RunTimeException
      RunTimeException               is-a Exception 

Exceptions and polymorphism

  • We can catch more general exceptions using exception types higher up in the exception hierarchy.

    Example:

        public static void main(String[] args)
        {
            int[] a = new int[10];
    
            // Index out of range
            try
            {
                a[99] = 1;
            }
            catch (Exception e)   // Higher up in hierarchy
            {
    	    System.out.println(e);
            }
        }

  • Use Exception will catch all types of exceptions

DEMO: 04-inheritance/25-exception/Demo2.java

Exceptions and polymorphism

  • You can use multiple catch clauses:

        public static void main(String[] args)
        {
            int[] a = new int[10];
    
            // Index out of range
            try
            {
                if ( Math.random() < 0.5 )
    	        a = null;
                a[99] = 1;
            }
            catch (ArrayOndexOutOfBoundsException e)
            {
    	    System.out.println(e);
            }
            catch (Exception e)
            {
    	    System.out.println(e);
            }
        }

  • You must use more specific exceptions first

DEMO: 04-inheritance/25-exception/Demo3.java