8. exceptionsjcor1/oop/oop9.pdf · java exception types • exceptions generated by the java...

30
CSA1012 - Joseph Cordina(C) 8. Exceptions Objectives By the end of this session, you should be able to: write Java/C# code that can handle error conditions ‘raised’ by the methods it calls write Java/C# methods that use exceptions to return errors create exception classes

Upload: others

Post on 20-Jun-2020

21 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

8. Exceptions

Objectives

By the end of this session, you should be able to:

• write Java/C# code that can handle error conditions ‘raised’ by the methods it calls

• write Java/C# methods that use exceptions to return errors

• create exception classes

Page 2: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Exceptions for You

• How do you handle errors ?• What if you have 20 similar

types of errors that could occur, what do you do ?

• What if all errors are widely different ?

• What if you need to deal with it all the way in the display layer?

• End result of your code ?

Page 3: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Traditional Error Handling

• Traditional error handling often relies on special error codes returned from a function in case of error

• Example: the Unix intread(…) system call:– returns zero to mean end of file– returns –1 and sets a global

error code on input error

Page 4: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Traditional Error Handling (con’t)

• Problems with error value return:– varies from program to

program, programmer to programmer

– return codes can be unusual or obscure

– context information is lost

Page 5: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Java/C# Exceptions• Java/C# provides exceptions

as a mechanism for error reporting and handling

• Exception reporting is:– supported by the Java/C# language– is application-general– independent of normal method return

value

• An exception is an object that describes a failure case:

– base class:java.lang.Exception [Java]

System.Exception [C#]

– some exception subclasses are defined by the Java/C# run-time ex.ArrayIndexOutOfBoundsException

– the programmer may also define exception classes

Page 6: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Java/C# Exceptions (con’t)

• When an error is detected, the method that detects it can throw an exception:– the calling code can define an

exception handler to catch the exception and respond to the error. Otherwise it can pass on the error or it can throw the error again.

Page 7: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Java/C# Exceptions (Con’t)

• If an exception is not caught, it causes execution to terminate with an error message, it falls off !

method c()

method b()

method main()

method a()

call trace

Exception thrown here. Caught here? If not

or here?

or here?

or here?

Page 8: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Creating an Exception Class

• Example of creating an exception class:

class MyException extendsException

{}class MyException:

ApplicationException{}

• Exceptions can carry a detail message, which must be set in the constructor. This helps in the exception containing information about itself !!

Page 9: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Creating an Exception Class

class MyException extends Exception

{MyException(String message){

super(message) ;}

}

• The message is exported through the getMessage()method:public String getMessage()

Page 10: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The throw Statement

• To throw an exception, use the statement:

throw exception object;• The object thrown is typically

instantiated in the throwstatement:if (a < 10){

throw new MyException (“value is less than 10”);

}

• The method that executes a throw is interrupted (as if it executed a return)

Page 11: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Defining an Exception Handler

• To handle an exception, the code that generates the exception must be enclosed within a try statement

• Following the try statement must be one or more catch statements, one for each type of exception being handled:

try {dangerousMethod ();

} catch (MyException e) {System.err.println(e.getMessage());

}

Page 12: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The catch Statement

• A catch statement has exactly one parameter, which must be of a class type

• A catch statement’s parameter matches an exception type if:

- the types are identical, or- the parameter type is a superclass

of the exception type, or- the parameter type is an interface

the exception type implements

Page 13: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The catch Statement(con’t)

• When an exception is thrown within a try statement:– the first catch statement with a

matching parameter executes– if no catch statement matches,

the method terminates– only the first matching catch

statement is executed; other matching catch statements are skipped

Page 14: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The catch Statement (Con’t)

• After the catch statement executes:– the program continues after the

try … catch block– unless the catch statement

finishes by executing a return, throw, break or continue

– it is not possible to return to the point where the exception occurred

Page 15: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The catch Statement (Con’t)

try {a[i] = 100;dangerousMethod ();

…} catch(ArrayIndexOutOfBoundsException a){

//ignore} catch (MyException m) {

return false;} catch (Exception e) {

System.out.println(“What’s this? “+e);

throw e;}

Page 16: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The finallyStatement

• A finally statement can appear at the end of a try…catch block

• A finally statement defines code that must be executed if any part of the preceding try block is executed

• If a local catch block catches an exception:– the catch code runs first, then– then finally block is executed

Page 17: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The finallyStatement (con’t)

• If an uncaught exception is thrown:– the finally block is executed first,

then– the current method exits

• finally {…} block is always executed, even after break, continue, return, or another throw.

• but, not after System.exit(0). This terminates the program before the finally statement

Page 18: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The finallyStatement (Con’t)

Example of finally statements:

//Suppose a method which locks an//object and this object must be// left “locked” for as short a // time as // possible …obj.lock();

Page 19: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The finallyStatement (Con’t)

try {dangerousMethod ();

} catch (MyException m) {// the finally statement// executes// before this return!return false;

} finally {obj.unlock ();

}

Page 20: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Java Exception Types

• Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException

• These include:- ArithmeticException- NullPointerException- ClassCastException - NegativeArraySizeException- ArrayIndexOutOfBoundsException- OutOfMemoryException

Page 21: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Java Exception Types(con’t)

• Other predefined exception types:

- ClassNoFoundException- NoSuchMethodException- InstantiationException- InterruptedException

Page 22: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The throws Clause in Java

• In Java if a method throws an exception:– it must also catch the exception, or– declare its intent to throw that type of

exception in its declaration using the keyword throws:

public int getVal() throws Exception{…

}

Page 23: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

The throws Clause in Java (con’t)

public int XX () throws Ex1, Ex2 {… // place where Ex1 and Ex2 are

// thrown}

• Likewise, if a method invokes another method that throws an exception, the invoking method must either:– catch the exception, or– cover that type of exception in its throws clause

• Subclasses of RuntimeException are excluded from this rule (called unchecked)

Page 24: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Constructors and Exceptions

• A constructor can also throw an exception

• The instantiation of the object whose constructor throws an exception must be within the try-catch block

• In Java over-loaded methods need not all conform to the throws clause

Page 25: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Summary

• Exceptions are objects that are thrown to signal an error

• Syntax for handling an exception uses:

try {…} catch (Exception excptn) {…} finally {…}

• To generate an exception with throw exception object;

• In Java a method must declare the types of exceptions it can throw using throws

Page 26: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Quiz

1. Find the compiler error in the following code.

try { String str = “have you found it

yet?”;str.charAt(-1);

} catch (ArrayIndexOfBoundsError){}

Page 27: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Quiz (con’t)2. What does the following code

fragment print?char[] arr = new char [10]; try {

arr[10] = ‘A’;} catch (RuntimeException e) {

System.out.println (“D E F”);throw e;

} finally {System.out.println (“G H I”);

}

Page 28: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Answers to Quiz

1. The parameter to the catch statement requires a name.

2. DEFGHI

Page 29: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Exercises

1. Write a test program that instantiates a String and initializes it to some non-null value. Attempt to access a character beyond the end of the string (you may use the charAt() method). What happens when you run the program?

2. Modify your test program to catch the exception and print the exception’s message (use the exception’s getMessage()method).

Page 30: 8. Exceptionsjcor1/OOP/OOP9.pdf · Java Exception Types • Exceptions generated by the Java run-time system are subclasses of java.lang.RuntimeException • These include: - ArithmeticException

CSA1012 - Joseph Cordina(C)

Exercises (con’t)

3. Revisit your Clock class. Modify the setTime() method to throw an exception of type BadTime if any of the hour, minutes or seconds values are out of range. Now create the BadTime class. It should extend the Exception class and define two constructors, one with no arguments and one with a String argument that specifies the error message. Test your modified setTime()method and your new exception class.