Unformatted text preview:

In this lecture, you will learn…What is an exception?Exception TerminologyWhy use exceptions?Decoding Exception MessagesException Message FormatException Messages Mini Pop-QuizThrowing ExceptionsHandling ExceptionsHandling Multiple ExceptionsFinally BlockTry-Catch-Finally BlockUnchecked ExceptionsChecked ExceptionsHandling Checked ExceptionsException Class HierarchyExceptions and InheritanceWriting Your Own ExceptionsWriting Your Own ExceptionsChecked or Unchecked?Lecture SummaryLecture SummaryMIT-AITI Lecture 14: ExceptionsHandling Errors with ExceptionsKenya 2005©2005MIT-Africa Internet Technology InitiativeIn this lecture, you will learn…• What an exception is• Some exception terminology• Why we use exceptions• How to cause an exception• How to deal with an exception• About checked and unchecked exceptions• Some example Java exceptions• How to write your own exception©2005MIT-Africa Internet Technology InitiativeWhat is an exception?• 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©2005MIT-Africa Internet Technology InitiativeException Terminology• 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©2005MIT-Africa Internet Technology InitiativeWhy use exceptions?• Compilation cannot find all errors• To separate error handling code from regular code – Code clarity (debugging, teamwork, etc.)– Worry about handling error elsewhere• To separate error detection, reporting, and handling• To group and differentiate error types– Write error handlers that handle very specific exceptions©2005MIT-Africa Internet Technology InitiativeDecoding Exception Messagespublic class ArrayExceptionExample {public static void main(String args[]) {String[] names = {“Bilha", “Robert"};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.java:4)©2005MIT-Africa Internet Technology InitiativeException Message Format •Exception messages have the following format:[exception class]: [additional description of exception] at [class].[method]([file]:[linenumber])©2005MIT-Africa Internet Technology InitiativeException Messages Mini Pop-Quiz• Exception message from array examplejava.lang.ArrayIndexOutOfBoundsException: 2 at ArrayExceptionExample.main(ArrayExceptionExample.java:4)• What is the exception class?java.lang.ArrayIndexOutOfBoundsException• Which array index is out of bounds?2• What method throws the exception? ArrayExceptionExample.main• What file contains the method?ArrayExceptionExample.java• What line of the file throws the exception? 4©2005MIT-Africa Internet Technology InitiativeThrowing Exceptions• All methods use the throw statement to throw an exception– if (student.equals(null))throw new NullPointerException();• The throw statement requires a single argument: a throwable object• Throwable objects are instances of any subclass of the Throwable class– Include all types of errors and exceptions– Check the API for a full listing of throwableobjects©2005MIT-Africa Internet Technology InitiativeHandling Exceptions• You can use a try-catch block to handle exceptions that are throwntry {// code that might throw exception}catch ([Type of Exception] e) {// what to do if exception is thrown}©2005MIT-Africa Internet Technology InitiativeHandling Multiple Exceptions• You can handle multiple possible exceptions by multiple successive catch blockstry {// code that might throw multiple // exceptions}catch (IOException e) {// handle IOException}catch (ClassNotFoundException e2) {// handle ClassNotFoundException}©2005MIT-Africa Internet Technology InitiativeFinally Block• You can also use the optional finally block at the end of the try-catch block • The 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©2005MIT-Africa Internet Technology InitiativeTry-Catch-Finally Blocktry {// code that might throw exception}catch ([Type of Exception] e) {// what to do if exception is thrown}finally {// statements here always get// executed, regardless of what // happens in the try block}©2005MIT-Africa Internet Technology InitiativeUnchecked Exceptions• Unchecked exceptions or runtime exceptionsoccur 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)• A method does not have to catch or specify that it throws unchecked exceptions, although it may©2005MIT-Africa Internet Technology InitiativeChecked Exceptions• Checked exceptions or nonruntimeexceptions are exceptions that occur in code outside of the Java runtime system• For example, exceptions that occur during I/O (covered next lecture) are nonruntime exceptions • The compiler ensures that nonruntimeexceptions are caught or are specified to be thrown (using the throws keyword)©2005MIT-Africa Internet Technology InitiativeHandling Checked Exceptions• Every method must catch checked exceptions OR specify that it may throw them (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");}} ORvoid readFile(String filename) throws FileNotFoundException {FileReader reader = new FileReader("myfile.txt");// read from file . . .}©2005MIT-Africa Internet Technology InitiativeException Class


View Full Document

MIT SP 772 - Exceptions

Download Exceptions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Exceptions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Exceptions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?