applets & applications csc 171 fall 2001 lecture 15
Post on 20-Dec-2015
216 views
TRANSCRIPT
Applets & ApplicationsApplets & Applications
CSC 171 FALL 2001
LECTURE 15
History: FORTRANHistory: FORTRAN1954 - John Backus
proposed the development of a programming language that would allow uses to express their problems in commonly understood mathematical formulae -- later to be named FORTRAN
Change in ScheduleChange in Schedule 11/12 – Chapter 14 – Exception Handling 11/16 – Midterm – Hoyt – 8AM 11/19 – Chapters 11, 12, & 13
– Graphics & GUIs (optional)– Enjoy the Turkey
11/26 – Chapter 16 – Files & Streams 11/29 – Project due 12/3 – Chapter 19 – Data Structures 12/11 – last lecture 12/19 – FINAL EXAM - 12/19 4PM
Exam Friday 11/16Exam Friday 11/16
8 AM - 9 AM Hoyt Chapters 1-10 –
– end of chapter questions make good study materiel
Labs Projects Workshops Multiple choice (20 @ 2%) Some “Write a method/class that . . .” (10 @ 6%)
Throwing ExceptionsThrowing Exceptions
What should a method do when a problem is detected?
Traditionally, methods return some special code to indicate failure
However,– The caller may forget to check the return value– The caller may not be able to fix it
Problems with return signalsProblems with return signals
If the caller forgets to check– Bad data is processed
String input = myTextBox.getText();
Double d = new Double(input); // what if I type “hello”
i = d.doubleValue();
If the caller can’t fix it – We have to punt to the caller’s caller
x.doStuff(); // becomes
If (!x.doStuff()) return false; //man, that’s a lot of code
Exception-handling Exception-handling mechanism to the rescuemechanism to the rescue
Exceptions can’t be overlookedExcepts can be handled by a competent
handler– Not just the caller
Simple Try Block SyntaxSimple Try Block Syntax
try {statement;statement;
}catch (ExceptionClass ExceptionObject) {
statement;statement;
}
Example: Console InputExample: Console Input
import java.io.*; public class ReadingDoubles {
public static void main (String[] args) { double i, j ;try {
// open the console for bufferd I/O InputStreamReader reader =
new InputStreamReader(System.in); BufferedReader console =
new BufferedReader(reader);
AlternatelyAlternately// instead of
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
// could use nested constructorsBufferedReader console = new BufferedReader(new InputStreamReader(System.in));
What happens?What happens?
public static void main (String[] args) { BufferedReader console =
new BufferedReader(InputStreamReader(System.in));
System.out.print("Please enter a floating point number : "); String input = console.readLine(); Double d = new Double(input); double d1 = d.doubleValue(); }
This happensThis happenscd d:/courses/CSC171/CSC171FALL2001/code/d:/devenv/jdk1.3/bin/javac Console1Bad.javaConsole1Bad.java:14: unreported exception java.io.IOException; must
be caught or declared to be thrownString input = console.readLine(); //read a String
^1 error
Compilation exited abnormally with code 1 at Mon Nov 12 21:14:52
Deal with the potential Deal with the potential exceptionexception
try { String input = console.readLine(); } catch (IOException e) {
System.out.println(e + “bad read”);System.exit(0);
}
ExampleExample
//get the valueSystem.out.print("Please enter a floating point number : "); try { input = console.readLine(); //read a String}catch (IOException e) { System.out.println(e + " bad read "); System.exit(0);}
Now check the number formatNow check the number formattry{
Double d = new Double(input); double d1 = d.doubleValue(); // Calculate the sum & printout System.out.println(d1 + "^2 == " + (d1*d1));}catch (NumberFormatException e) { System.out.println(e +
" : What you entered was not a double");}
Checked & Unchecked Checked & Unchecked ExceptionsExceptions
Java Exceptions fall into two categories– Checked
You MUST tell the compiler what you are going to do about the exception
– Unchecked (sub-classes of RuntimeException) NumberFormatException IllegalArgumentException NullPointerException
Exception Class HierarchyException Class Hierarchy
Why Checked & Unchecked?Why Checked & Unchecked?
Checked Exceptions are not your fault– So, you have to deal with them
Unchecked Exceptions are your fault– So, we trust you to deal with them
You have to deal with things you cannot prevent!
Cheap hacksCheap hacks1. Lazy empty clauses
try {System.in.read()}
catch (IOException e){}
2. Punt the exception to the callerpublic static void main(String[] args) throws
IOException
Alternate version IAlternate version I
import java.io.*; public class ReadingDoubles3{ public static void main (String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);BufferedReader console = new BufferedReader(reader);
//get the first valueSystem.out.print("Please enter a floating point number : ");
String input = console.readLine(); //read a StringDouble d = new Double(input); double d1 = d.doubleValue();
Alternate Version IIAlternate Version II
// Calculate the sum & printoutSystem.out.println(d1 + "^2 == " + (d1*d1));
// wait for user to endSystem.out.println(" Hit return to exit");System.in.read();
}}
Throwing your own exeptionsThrowing your own exeptions
public static double myfun(double ValueBetweenZeroAndOne) {if ((ValueBetweenZeroAndOne < 0) ||
( ValueBetweenZeroAndOne > 1)) throw new IllegalArgumentException("RTFM - you dolt!");return ValueBetweenZeroAndOne * ValueBetweenZeroAndOne;
}
Making them deal with itMaking them deal with it
public static double myfun(double ValBetZeroAndOne) throws
Exception { // now, they have to write a handlerif ((ValBetZeroAndOne < 0) || ( ValBetZeroAndOne > 1)) throw new IllegalArgumentException("RTFM – you dolt!");return ValBetZeroAndOne * ValBetZeroAndOne;
}
Defining your own exceptionsDefining your own exceptions
public class DivideByZeroException extends RuntimeException {
public DivideByZeroException() {super(“Attempt to divide by Zero”);
} public DivideByZeroException( String msg) {
super(msg);}
}
Defining your own checked Defining your own checked exceptionsexceptions
public class myCheckException extends Exception {public myCheckException() {
super(“Attempt to divide by Zero”);}
public myCheckException( String msg) {super(msg);
}}
FinallyFinallytry {
statements;}catch (ExceptionClass ExceptionObject) {
statements; //exception specific} finally {
statements; //clean up}
FinallyFinally
The Finally block executes regardless of what happens in the try/catch
Good for cleaning up resourcesGood for conditions where the catch blocks
may throw exceptions.