Download presentation
Presentation is loading. Please wait.
Published byBartholomew Lane Modified over 9 years ago
1
Input/Ouput and Exception Handling
2
2 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught
3
3 Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program The manner in which an exception is processed is an important design consideration
4
4 Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that indicates the line on which the exception occurred The call stack trace also shows the method call trail that lead to the attempted execution of the offending line The getMessage method returns a string explaining why the exception was thrown The printStackTrace method prints the call stack trace See Zero.java Zero.java
5
5 Exception Handling public class Zero { // Deliberately divides by zero to produce an exception. public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } } Exception in thread "main" java.lang.ArithmeticException: / by zero at Zero.main(Zero.java:8)
6
6 The try Statement To process an exception when it occurs, the line that throws the exception is executed within a try block A try block is followed by one or more catch clauses, which contain code to process an exception Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the exception type See ProductCodes.java ProductCodes.java
7
7 The finally Clause A try statement can have an optional clause following the catch clauses, designated by the reserved word finally The statements in the finally clause always are executed If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete
8
8 Exception Propagation An exception can be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method A try block that contains a call to a method in which an exception is thrown can be used to catch that exception See Propagation.java Propagation.java See ExceptionScope.java ExceptionScope.java
9
9 Exception Handling >java Propagation Program beginning. Level 1 beginning. Level 2 beginning. Level 3 beginning. The exception message is: / by zero The call stack trace: java.lang.ArithmeticException: / by zero at ExceptionScope.level3(ExceptionScope.java:54) at ExceptionScope.level2(ExceptionScope.java:41) at ExceptionScope.level1(ExceptionScope.java:18) at Propagation.main(Propagation.java:17) Level 1 ending. Program ending.
10
10 The throw Statement A programmer can define an exception by extending the Exception class or one of its descendants Exceptions are thrown using the throw statement Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown When an exception is thrown, method terminates immediately Execution continues with an exception handler
11
public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }... } Example
12
Hierarchy of Exception Classes
13
13 Checked Exceptions Two types of exceptions: Checked oThe compiler checks that you don't ignore them oDue to external circumstances that the programmer cannot prevent oMajority occur when dealing with input and output oFor example, IOException Unchecked: oExtend the class RuntimeException or Error oThey are the programmer's fault oExamples of runtime exceptions: NumberFormatException IllegalArgumentException NullPointerException oExample of error: OutOfMemoryError
14
14 Checked Exceptions An exception is either checked or unchecked A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it A throws clause is appended to the method header The compiler will issue an error if a checked exception is not handled appropriately
15
Unchecked Exceptions An unchecked exception does not require explicit handling, though it could be processed that way The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants Errors are similar to RuntimeException and its descendants Errors should not be caught Errors do not require a throws clause
16
I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information to an output stream A program can manage multiple streams simultaneously
17
I/O Streams The java.io package contains many classes that allow us to define various streams with particular characteristics Some classes assume that the data consists of characters Others assume that the data consists of raw bytes of binary information Streams can be further subdivided as follows: data stream, which acts as either a source or destination processing stream, which alters or manipulates the basic data in the stream
18
I/O Streams Character Streams Byte Streams Data Streams Processing Streams Input Streams Output Streams
19
Character vs. Byte Streams A character stream manages 16-bit Unicode characters A byte stream manages 8-bit bytes of raw binary data A program must determine how to interpret and use the bytes in a byte stream Typically they are used to read and write sounds and images The InputStream and OutputStream classes (and their descendants) represent byte streams The Reader and Writer classes (and their descendants) represent character streams
20
Data vs. Processing Streams A data stream represents a particular source or destination such as a string in memory or a file on disk A processing stream (also called a filtering stream) manipulates the data in the stream It may convert the data from one format to another It may buffer the stream
21
The IOException Class Operations performed by the I/O classes may throw an IOException A file intended for reading or writing might not exist Even if the file exists, a program may not be able to find it The file might not contain the kind of data we expect An IOException is a checked exception
22
Standard I/O There are three standard I/O streams: standard input – defined by System.in standard output – defined by System.out standard error – defined by System.err System.in typically represents keyboard input System.out and System.err typically represent a particular window on the monitor screen We use System.out when we execute println statements
23
Writing Text Files To write to a file, construct a PrintWriter object PrintWriter out = new PrintWriter("output.txt"); If file already exists, it is emptied before the new data are written into it If file doesn't exist, an empty file is created Use print and println to write into a PrintWriter : out.println(29.95); out.println("Hello, World!"); You must close a file when you are done processing it: out.close(); Otherwise, not all of the output may be written to the disk file When the input or output file doesn't exist, a FileNotFoundException can occur
24
Reading Text Files Information can be read from and written to text files by declaring and using the correct I/O streams The FileReader class represents an input file containing character data The FileReader and BufferedReader classes together create a convenient text file output stream See CheckInventory.java CheckInventory.java See InventoryItem.java InventoryItem.java
25
Reading Text Files Simplest way to read text: use Scanner class To read from a disk file, construct a FileReader Then, use the FileReader to construct a Scanner object FileReader reader = new FileReader("input.txt"); Scanner in = new Scanner(reader); Use the Scanner methods to read data from file next, nextLine, nextInt, and nextDouble
26
A Sample Program Reads all lines of a file and sends them to the output file, preceded by line numbers Sample input file: Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go! Program produces the output file: /* 1 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go! Program can be used for numbering Java source files
27
fileio/LineNumberer.java 01: import java.io.FileReader; 02: import java.io.FileNotFoundException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06: public class LineNumberer 07: { 08: public static void main(String[] args) 09: throws FileNotFoundException 10: { 11: Scanner console = new Scanner(System.in); 12: System.out.print("Input file: "); 13: String inputFileName = console.next(); 14: System.out.print("Output file: "); 15: String outputFileName = console.next(); 16: 17: FileReader reader = new FileReader(inputFileName); 18: Scanner in = new Scanner(reader); 19: PrintWriter out = new PrintWriter(outputFileName); 20: int lineNumber = 1;
28
fileio/LineNumberer.java (cont.) 21: 22: while (in.hasNextLine()) 23: { 24: String line = in.nextLine(); 25: out.println("/* " + lineNumber + " */ " + line); 26: lineNumber++; 27: } 28: 29: out.close(); 30: } 31: }
29
File Dialog Boxes Continued
30
File Dialog Boxes (cont.) JFileChooser chooser = new JFileChooser(); FileReader in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); reader = new FileReader(selectedFile);... }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.