public void bar thisbaz systemoutprintlnhere

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: –  e.g. Math.sqrt returns NaN ("not a number") if given input < 0 e.g. Many Java libraries return null e.g. file reading method returns - 1 if no more input available Caller must check return value Use with cau5on – easy to introduce hard to find bugs •  Use an informaAve result –  e.g. in OCaml we used opAons to signal potenAal failure –  e.g. in Java, create a special class like opAon –  Passes responsibility to caller, but caller must do the proper check •  Use excepAons –  Available both in OCaml and Java –  Any caller can handle the situaAon –  If excepAons are uncaught, the program terminates CIS120 / Spring 2012 ExcepAons Dealing with the unexpected. ExcepAons •  An excepAon is an object represenAng abnormal condiAons. –  Its internal state describes what went wrong –  e.g. NullPointerExcepAon, IllegalArgumentExcepAon, IOExcepAon –  Can define your own excepAon classes •  Throwing an excepAon is an emergency exit from the current method. –  The excepAon propagates up the invocaAon stack unAl it either reaches the top and the stack, in which case the program aborts with the error, or the excepAon is caught •  Catching an excepAon lets callers take appropriate acAons to handle the abnormal circumstances CIS120 / Spring 2012 RealisAc Example void loadImage (String fileName) { try { Picture p = new Picture(fileName); // could fail // ... code to display the new picture in the window // executes only if the picture is successfully created. } catch (IOException ex) { }! // Use the GUI to send an error message to the user // using a dialog window JOptionPane.showMessageDialog( frame, // parent of dialog window // error message to display "Cannot load file\n" + ex.getMessage(), "Alert", // title of dialog JOptionPane.ERROR_MESSAGE // type of dialog ); CIS120 / Spring 2012 Simplfied Example class C {! !public void foo() {! ! !;! ! !System.out.println(“here in foo”);! !}! !public void bar() {! ! !this.baz();! ! !System.out.println(“here in bar”);! !}! !public void baz() {! ! !throw n...
View Full Document

This document was uploaded on 11/24/2013.

Ask a homework question - tutors are online