Docsity

Exceptions in Java: Understanding and Handling Errors - Prof. Bonnie J. Dorr, Study Guides, Projects, Research of Computer Science

Partial preview of the text

Download Exceptions in Java: Understanding and Handling Errors - Prof. Bonnie J. Dorr and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Lecture 30: Exceptions

Last time: 1.

Packages

Today 1.

Exceptions

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Project #6 Assigned! z

Project due Monday, 4/16 at 11 pm

z

Project is closed z

You must complete the project by yourself

z

Assistance can only be provided by teaching assistants(TAs) and instructors

z

You must not look at other students' code

z

Start now! z

Read entire assignment from beginning to end beforestarting to code

z

Check out assignment now from CVS

z

Follow the instructions exactly , as much of grading is automated

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Exception Behavior z

If program generates (“throws”) exception then default behavior is: z

Java clobbers (“aborts”) the program

z

Stack trace is printed showing where exception was generated
z

Example

public static int findIndex(int[] ints, int s){
for (int ret = 0; ret <= ints.length; ret++)
if (ints[ret] == s)
return ret;
return -1;

z

Consider: int[] ints = {0, 2, 1, 5};

z

Evaluating
findIndex(ints, 6)
results in:
Exception
in
thread
"main"
java.lang.ArrayIndexOutOfBoundsException:
at
exceptionExamples.SearchExample.findIndex(SearchExample.java:13)
at
exceptionExamples.SearchExample.main(SearchExample.java:27)

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Handling Exceptions z

Aborting program not always a good idea z

E-mail: can’t lose messages

z

E-commerce: must ensure correct handling ofprivate info in case of crash

z

Antilock braking, air-traffic control: must recoverand keep working

z Java includes mechanisms for recoveringfrom exceptions

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Java Exceptions in Detail z

Exceptions are (special) objects in Java z

They are created from classes

z

The classes are derived (“inherit”) from a special class,Throwable

z

We will learn more about inheritance, etc., later

z

Every exception object / class has: z

Exception(String message) Constructor taking an explanation as an argument

z

String getMessage() Method returning the embedded message of the exception

z

void printStackTrace() Method printing the call stack when the exception was thrown

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Exceptions, Classes andTypes z

Exceptions are objects z In Java, objects are created from classes z Classes are also types z Are there exception classes in Java? Yes! Some examples from theJava class library (mostly java.lang): z ArithmeticException : Used e.g. for divide by zero

z

NullPointerException : attempt to access an object with a null reference

z

IndexOutOfBoundsException : array or string index out of range

z

ArrayStoreException : attempting to store wrong type of object in array

z

EmptyStackException : attempt to pop an empty Stack (java.util)

z

IOException : attempt to perform an illegal input/output operation (java.io)

z

NumberFormatException : attempt to convert an invalid string into a number (e.g., when calling Integer.parseInt( ) )

z

RuntimeException : general run-time error (subsumes above)

z

Exception : The most generic type of exception

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Example z

Recall previous findIndex example

z

What is output? public static void main(String[] args) {
int[] ints = {0, 2, 1, 5}; try {
System.out.print ("Searching for 6.
System.out.println ("Index is " + findIndex(ints, 6));
} catch (IndexOutOfBoundsException e) {
System.out.println ("\nThere must be an array error."); System.out.println ("Message is:
" + e.getMessage());

z

Answer: Searching for 6. There must be an array error. Message is:

4

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Exception Propagation z

In previous example: z Exception thrown in one method (findIndex) … z … but caught in another (main)

z

Java uses exception propagation to look for exception handlers z When an exception occurs, Java pops back up the call stack toeach of the calling methods to see whether the exception is beinghandled (by a try-catch block). This is exception propagation z The first method it finds that catches the exception will have itscatch block executed. Execution resumes normally in the methodafter this catch block z If we get all the way back to main and no method catches thisexception, Java catches it and aborts your program

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Example: What Is Output? public

class EasyExample { public static void g(boolean b) { System.out.println ("Entering g ..."); if (b) throw new RuntimeException("Oh no, you really messed up..."); System.out.println ("Exiting g ..."); } public static void f(int i) { System.out.println ("Entering f ..."); g(i == 0); System.out.println ("Exiting f ..."); } public static void main(String[] args) { try { f(1); } catch (RuntimeException e) { System.out.print ("Runtime error. Message: "); System.out.println (e.getMessage()); } } }

CMSC 131 Spring 2007 Bonnie Dorr (adapted from Rance Cleaveland)

Example: Handling more thanone exception?

public static void main(String[] args) { String d = ""; try { d = JOptionPane. showInputDialog ("Enter date: (mm/dd/yyyy)"); int year = getYear (d); System. out .println("The year is "

year); } catch (IndexOutOfBoundsException e) { System. out .println("index error"); } catch (NumberFormatException e) { System. out .println("Number format problem"); return ; // NOTE: finally block will still run!! } finally { System. out .println("Finally block is running now..."); } }