Download presentation
Presentation is loading. Please wait.
1
CSE 114 – Computer Science I Exceptions
Cape Breton, Nova Scotia
2
How should a method react to improper input?
Exit the program option: public Person(String initName, int initAge) { name = initName; if ((initAge < 0) || (initAge > 100)) System.exit(0); age = initAge; } Poor Option Program cannot recover if error condition occurs Programmer using this class may not anticipate error Use default value option: public Person(String initName, int initAge) { name = initName; if ((initAge < 0) || (initAge > 100)) age = 0; else age = initAge; } Poor Option Calling class not notified of error condition Prone to logical errors
3
Exception option public Person(String initName, int initAge)
throws InvalidAgeException { name = initName; if ( (initAge < 0) || (initAge > 100) ) throw new InvalidAgeException(initAge); else age = initAge; } InvalidAgeException is a class I defined for HW5 Good Option Program can recover if error condition occurs Programmer using this class is forced to anticipate a specific type of error Calling class immediately notified of error condition Helps to logical errors
4
Exceptions Objects that defines an erroneous condition in a program.
May be thrown in two ways: by JVM during runtime due to an illegal operation : ArithmeticException ClassCastException ArrayIndexOutOfBoundsException NumberFormatException NullPointerException by a program explicitly using throw May be caught in several ways: by an exception handler (you deal with it) by the operating system (runtime error)
5
Some Exceptions/Errors thrown by the JVM
bash-2.03$ javac Driver.java bash-2.03$ java Drivver Exception in thread "main" java.lang.NoClassDefFoundError: Drivver bash-2.03$ Misspelled class name Exception in thread "main" java.lang.NullPointerException This code generates this exception String dumb = null; int len = dumb.length(); Exception in thread "main" java.lang.ArithmeticException: / by zero This code generates this exception int i = 1, j = 0; i = i/j;
6
A Program generating and handling an Exception
double radius, area, circ, PI = 3.14; try { System.out.print("Input a circle radius: "); radius = keyboard.nextDouble(); if (radius <= 0.0) throw new Exception("ERROR: Invalid radius!"); area = PI * radius * radius; circ = 2.0 * PI * radius; System.out.println("radius: " + radius); System.out.println("area: " + area); System.out.println("circumference: " + circ); } catch (Exception e) { e.printStackTrace(); Exception is generated here Exception is handled here
7
Exception Handling When the throw statement is executed in a try block, an Exception object is created a String is passed to the constructor of the Exception object execution of the try block is suspended control passes to the catch block that is placed after the try block If the throw statement is not executed, execution of the try block is completed the corresponding catch block is ignored … try { throw new Exception(“…”); } catch (Exception e)
8
Line of error int total = 0, num = 0, avg; PrintStream o = System.out;
o.print("Enter total: "); total = keyboard.nextInt(); o.print("Enter num: "); num = keyboard.nextInt(); o.println("Before try"); try { o.println("Inside try, pre div"); avg = total/num; o.println("Inside try, post div"); o.println("Average: " + avg); } catch(Exception e) { o.println("Inside catch"); e.printStackTrace(); o.println("After catch"); bash-2.03$ java ExceptionTester Enter total: 6 Enter num: 3 Before try Inside try, pre div Inside try, post div Average: 2 After catch Message available via getMessage() method bash-2.03$ java ExceptionTester Enter total: 4 Enter num: 0 java.lang.ArithmeticException: / by zero at main(…java:16) Before try Inside try, pre div Inside catch After catch Line of error
9
Updated Example int total = 0, num = 0, avg;
PrintStream o = System.out; do { o.print("Enter total: "); total = keyboard.nextInt(); o.print("Enter num: "); num = keyboard.nextInt(); try avg = total/num; o.println("Average: " + avg); } catch(Exception e) o.println(e.getMessage()); } while (num == 0); Updated Example EXAMPLE SESSION: Enter total: 4 Enter num: 0 / by zero Enter total: 6 Enter num: 3 Average: 2
10
Predefined Exception Classes
There are many derived classes from the Exception class for specific types of errors. Some exception classes: IOException: A requested I/O operation could not be completed successfully. NumberFormatException: An operation was attempted using a number in an illegal format. NullPointerException: A null reference was used where an object reference was needed ex: method invocation Die die1 = null; die1.roll()
11
Example: Parsing ints public static int readInt(Scanner keyboard) { String token = keyboard.next(); int value; try value = Integer.parseInt (token); } catch (Exception exception) System.out.println ("Error reading int data, MIN_VALUE value returned."); value = Integer.MIN_VALUE; return value; For improper input, the parseInt method throws an NumberFormatException. Using the Exception class here catches all types of exceptions. Why? Automatic Type Casting
12
More on Exceptions Why pass exceptions?
An Exception can be passed to the calling method specifying your method throws specific exceptions means it can be handled (or again may be passed) by the calling method 2 types of exceptions: (1) Checked: Subclasses of RuntimeException ex: java.lang.NumberFormatException, from Sun’s JDK Calling class can call method with or without try-catch block (2) Unchecked: All other Exception classes ex: InvalidAgeException, a class I defined for HW5 Calling class must place call to method inside try-catch block Why pass exceptions? flexibility
13
Case (1) Examples Method from Integer class: public static int parseInt(String s) throws NumberFormatException Calling parseInt without try-catch: System.out.print("Enter text: "); String text = keyboard.next(); int num = Integer.parseInt(text); System.out.println(num); For improper input, the passed exception is not caught. Results in a runtime error & program terminates. Calling parseInt with try-catch: try { System.out.print("Enter text: "); String text = keyboard.next(); int num = Integer.parseInt(text); System.out.println(num); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } For improper input, the passed exception is caught. Program can continue.
14
Case (2) Example Constructor from Person class for HW5: public Person(String initName, int initAge) throws InvalidAgeException { name = initName; if ( (initAge < 0) || (initAge > 100) ) throw new InvalidAgeException(initAge); else age = initAge; } Must be inside try-catch block, else it is a syntax error Calling the above Person constructor with try-catch: Person mariano; try { mariano = new Person("Rivera, Mariano", 39)); } catch (InvalidAgeException iae) { iae.printStackTrace(); } System.out.println(mariano); mariano is declared here so that it may be used outside the try block
15
Example: PassTheException
public class PassTheException { public static void pass() throws NullPointerException the(); } public static void the() throws NullPointerException exception(); public static void exception() throws NullPointerException String dumb = null; dumb.length();
16
Prints the history of exception passing
public static void main(String[] args) { try pass(); } catch(NullPointerException npe) { npe.printStackTrace(); } Results bash-2.03$ java PassTheException java.lang.NullPointerException at PassTheException.exception(PassTheException.java:16) at PassTheException.the(PassTheException.java:10) at PassTheException.pass(PassTheException.java:5) at PassTheException.main(PassTheException.java:23) bash-2.03$ Prints the history of exception passing
17
Defining Your Own Exception
When you insert a throw statement in your code you may use an existing exception class or you may define your own Exception class. Define a derived class from Exception or one of its descendants A constructor is usually all that is required: public class GradeException extends Exception { public GradeException() { super("ERROR: " + grade + " is an illegal value!“ + "\n\tGrades must be from "); } public GradeException(String s) { super(s);
18
Using Your Own Exception
public class GradeExceptionTester { public static final PrintStream o = System.out; public static int promptForGrade() throws GradeException int grade = 0; o.print("Please enter a grade: "); Scanner keyboard = new Scanner(System.in); grade = keyboard.nextInt(); if ((grade < 0) || (grade > 100)) throw new GradeException(grade); return grade; }
19
Using Your Own Exception
public static void main(String[] args) { int[] gradesArray = new int[5]; int counter = 0, total = 0; while (counter < 5) try gradesArray[counter] = promptForGrade(); total += gradesArray[counter]; counter++; } catch(GradeException ge) { o.println(ge.getMessage()); } o.println("Average grade: " + ((double)total/5));
20
GradeExceptionTester Output
bash-2.03$ java GradeExceptionTester Please enter a grade: 55 Please enter a grade: 66 Please enter a grade: 77 Please enter a grade: -5 ERROR: -5 is an illegal value! Grades must be from Please enter a grade: 88 Please enter a grade: 99 Average grade: 77.0 bash-2.03$
21
Catching Different Exceptions Separately
Sometimes there may be multiple sources of errors inside a single try block, for such cases you have 2 options: Use a common ancestor class to catch all exceptions Ex: Exception catch each type of exception separately (preferred) This allows your program to react differently to different types of problems
22
Multiple catches example
public static void savePersonName(Person p) throws NullPointerException { try FileOutputStream fos = new FileOutputStream("output.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(p.getName()); oos.close(); } catch(NotSerializableException nse) { o.println(“Remember to implement Serializable"); } catch(FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch(IOException ioe) { System.exit(0); }
23
Exceptions Ordering A single try block may have multiple catch blocks but, the order of the caught exceptions is important Only one catch block may be executed per try block execution So, descendent exception classes must be listed first Ex: try { number = Double.parseDouble(obj.getText()); } catch (Exception e) { e.printStackTrace(); } catch (NumberFormatException nfe) System.out.println(nfe.getMessage()); number = 0.0; This would produce a syntax error, because of unreachable code
24
Exceptions Ordering - Improvement
This catch block will handle NumberFormatExceptions try { number = Double.parseDouble(obj.getText()); } catch (NumberFormatException nfe) System.out.println(nfe.getMessage()); number = 0.0; catch (Exception e) { e.printStackTrace(); } This catch block will handle everything else.
25
What is data storage? The means by which a program stores its data
Can you name data associated with this program? How about your favorite game? How is this done? temporarily persistently
26
Temporary Data Data loaded into RAM Used for running program
stack, heap, and global segments of program space Used for running program primitives objects arrays What happens to this data (in RAM) when a program terminates? It’s gone Some other program will be given that region of RAM.
27
Persistent Data After a program ends, this data is not destroyed. Why?
Its not only (if at all) in RAM. Where is it then? Hard drive, CD, DVD, Server, i.e. permanent storage What on these devices store this data? files database (managed via a group of files)
28
How does temporary data get its values?
Potentially by many means. Ex: Values hard coded into a program: int i = 0; Program calculations: int i = j + 5; User input via a device & stream: int i = keyboard.nextInt(); The Computer’s System: int i = (int)(Math.random() * 100) + 1; An input stream from a file or server: int i = binaryFileReader.readInt(); A database: int i = resultSet.getInt("SALARY");
29
How does persistent data get its values?
An output stream in your program: printWriter.println(outputText); An output stream in some other program: Notepad Microsoft Word Maya Starcraft Campaign Editor Anything that can save files
30
Ex: Starcraft Starcraft Campaign Editor Starcraft
for making your own map level saves your and all necessary data to .scm file done via output stream Starcraft lets player pick map level to play loads all necessary data from .scm file done via input stream Note: this only works if Starcraft knows how the data in scm files is arranged
31
Let’s open the Fastest.scm map in Notepad
What happened? MPQ ã_ à Ã_ s(O쬓ÊÁÝ©ˆ¨ÀPæÒñwA'ŒŠ’'$¶›„qÚu!ÿA±7m_‘>Îû3®²E¿õµõ4‹‘.B¡]N™.>›ÝØ&ÜB,>Bži㥣ÂÛ?Ò€€¼âB´dqÝj|¨ç›4ê´Cº3Ñ.ÒÓõ(0J4q¶ñ~¢n‰¿wAŽÚY™×=nââpQ]À&¶‘©1,#õbw}ž}Ú5åNBˆÃYïŠ{sRøÃ¶‡Ë¤Vò_V˜i‰£k'CòÑœ]ñRꮟþ’å„à^Ÿ³fJêöÄòK}S~c«“¬$u\诣7<ºƒÚXAi¯LÃúvá·™õÙ^»W;õÄÇq»M˜p#´#ÈÎv …
32
I/O Streams Program I/O must work together
Input Streams must know how the Output Stream sent data: What data? What types? What format are the types? (not an issue in Java) What type of stream was used? In what order? I/O Streams typically use Sequential Access for output streams data appears in the file in the order it is written out for input streams: data is read from the file in the order it appears in the file
33
Sequential Access & Primitives
Output to file NumbersData.dat (binary) outputStream.writeInt(x); outputStream.writeInt(y); outputStream.writeInt(z); Input from file NumbersData.dat into variables int x = inputStream.readInt(); int y = inputStream.readInt(); int z = inputStream.readInt();
34
How about objects? An object is its data (instance variables)
Saving objects to a text/binary file: write out all of its instance variables do so in order (sequentially) Loading objects from a text/binary file: read in all of its instance variables use read data to construct an object
35
Sequential Access & Objects
Output to file PersonData.dat (binary) outputStream.writeUTF(p.getName()); outputStream.writeInt(p.getAge()); Input from file PersonData.dat into variables String initName = inputStream.readUTF(); int initAge = inputStream.readInt(); Person p = new Person(initName, initAge);
36
Java I/O Java has extensive support for I/O of all sorts
java.io.* package more than 60 different stream types Lots of features I/O to programs/files/Internet (files & servers) encoding compression encryption
37
Readers/Writers
38
Common Java Stream Types
Text BufferedReader/PrintWriter reads/writes Unicode Binary DataInputStream/DataOutputStream reads/writes bytes Object files (using Object Serialization) ObjectInputStream/ObjectOutputStream reads/writes Java objects
39
How much memory would be required:
To store the integer value 777 in a text file? 3 chars * 2 bytes per char == 6 bytes in a binary file? 1 int * 4 bytes per int == 4 bytes in a Java object file? lots more the context (meta data) and the data itself
40
Text Versus Binary Files
Text files: are readable (ex: Notepad) are a common format (think Unicode/ASCII) good for sharing files between programs think XML require data to be converted into text for output require data to be converted from text for input Binary files: can store data in its natural format typically requires less memory than text requires no conversion reading/writing from/to files is faster that text
41
Development vs. Release Formats
During project development: have program use text files readable helps with changing parameters helps with debugging When product is released have program use binary files less memory faster Note that this is an option, not a rule. XML is common throughout both stages
42
So how do we use Java’s streams?
Output streams: Open an output stream to a file While there is more data to write, do steps 3 & 4 Write data to file Go back to step 2 Close stream Input streams: Open an input stream to a file While there is more data to read, do steps 3-5 Read/write next piece of data Use read data to initialize proper variables Close the stream
43
Java’s Streams Streams have counters: When you write, it:
when you open a stream, counter is set to start of file denotes location in file to read/write from When you write, it: writes data to end of file counter moves to end of data just written the new end of file When you read, it: gets next piece of data counter moves to next piece
44
Writing to a text file in Java
To use java.io.PrintWriter Construct (open) the stream Write all text one line a time using println(…) Close stream when done (i.e. end of file)
45
Text File Writing Example
try { File file = new File("Output.txt"); Writer writer = new FileWriter(file); PrintWriter out = new PrintWriter(writer); out.println("Janie Jones"); out.println("" + 25); out.close(); } catch(IOException ioe) System.out.println("File not Found");
46
Reading from a text file in Java
To use java.io.BufferedReader Construct (open) the stream Read text one line at a time using readLine() readLine returns null if no more text to read Close stream when done (i.e. end of file)
47
Text File Reading Example
Person p; try { File file = new File("Output.txt"); Reader reader = new FileReader(file); BufferedReader in = new BufferedReader(reader); String name = in.readLine(); String ageText = in.readLine(); int age = Integer.parseInt(ageText); p = new Person(name, age); System.out.print(p); } catch(IOException ioe) System.out.println("File not Found"); Output? Janie Jones, 25
48
How much data does the file have?
Many times we don’t know A Web browser doesn’t know how much text is in Web page until it reads in the entire thing 2. Read text one line at a time using readLine() readLine returns null if no more text to read
49
I/O Example We have a file called grades.txt
It stores exam grades for entire class One grade per line. Ex: 90 77 … Read in all grade and calculate average Write N and average to stats.txt
50
Example import java.io.*; public class TextFileDemo {
public static void main(String[] args) try { BufferedReader inputStream = new BufferedReader (new FileReader("grades.txt")); PrintWriter outputStream = new PrintWriter (new FileOutputStream("stats.txt")); int count = 0, sum = 0; String line; line = inputStream.readLine(); while (line != null) // at EOF? { count++; sum += Integer.valueOf(line).intValue(); } Example
51
Example (cont’d) if (count != 0) { int average = sum / count;
outputStream.println("Number of students: " + count); outputStream.println("Class average: " + average); } else outputStream.println("No grades to average."); inputStream.close(); outputStream.close(); catch (FileNotFoundException e) { System.out.println(e.getMessage() + "\nFile not found.");} catch (IOException e) + "\nError accessing file");} } // main } // class
52
What’s the delimiter here?
Delimited Text How about saving Person objects to one text file? One line per variable is not very readable: Joe 16 Jane 26 George 13 Using delimited data is better: Joe|16 Jane|26 George|13 What’s the delimiter here? |
53
Choosing Delimiters We might want each line to represent an object
Common delimiters: ‘|’, ‘:’, ‘-’ What about ‘\t’? What about ‘,’? Example file for Employee objects: Wayland Smithers|38|100000 Ned Flanders|37|60000 Selma Bouvier|45|40000 Tab-separated values Comma-separated values (csv)
54
Writing Delimited Output
How would we save an array of Employees? Construct PrintWriter stream to file For each student in array: build String with all data on one delimited line. Ex: Wayland Smithers|38|100000 Write line to file Close stream
55
Reading Delimited Output
Requires parsing of delimiters Construct BufferedReader stream to file For each line in the file: break line into pieces (parse) construct object from pieces assign new object to variable or entry in array Close stream
56
How might we parse our line of text?
String methods we could look for delimiter indices (indexOf) extract substrings using indices (substring) Use split method also from String class returns array of text divided by delimiters delimiter as regular expression use ‘-’ instead of ‘|’ Use java.util.StringTokenizer
57
Splitting a String Example
String test = "Wayland Smithers "; String[] array = test.split("-"); System.out.println(array.length); for (int i = 0; i < array.length; i++) System.out.println(array[i]); Note that I have hard coded test, but we could also have read it as a line from a text file 3 Wayland Smithers 38 100000 What’s the output?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.