Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.

Similar presentations


Presentation on theme: "Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA."— Presentation transcript:

1 Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA

2 What Is an Exception  Exception is an event where something abnormal happens.  When an error occurs within a method, the method creates an exception object with various information about the event. We call this throwing an exception.  The call stack refers to the ordered list of methods called when you get to where the exception occurred.

3 What Is an Exception Cont.  You can handle the exception by creating a handler that matches that specific type.  For example, catching an FileNotFoundException  This is called catching the exception  If the exception is not caught, the program is terminated.

4 Types of Exceptions  There are three main types of exceptions  Checked Exceptions  Errors  Runtime Exceptions

5 5 Exception Types

6 6 System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

7 7 Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

8 8 Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

9 9 Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.

10 10 Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.

11 11 Unchecked Exceptions Unchecked exception.

12 12 Declaring, Throwing, and Catching Exceptions

13 13 Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException

14 14 Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex;

15 15 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

16 16 Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; }... catch (ExceptionN exVar3) { handler for exceptionN; }

17 17 Catching Exceptions

18 18 Catch or Declare Checked Exceptions Suppose p2 is defined as follows:

19 19 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b).

20 20 Rethrowing Exceptions try { statements; } catch(TheException ex) { perform operations before exits; throw ex; }

21 21 The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }

22 22 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements

23 23 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed

24 24 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed

25 25 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2

26 26 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.

27 27 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.

28 28 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method is now executed.

29 29 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; statement2 throws an exception of type Exception2.

30 30 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handling exception

31 31 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Execute the final block

32 32 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Rethrow the exception and control is transferred to the caller

33 33 Cautions When Using Exceptions  Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify.  Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

34 34 When to Throw Exceptions  An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.

35 35 When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }

36 36 When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");

37 Text File I/O Heavily Borrowed from https://docs.oracle.com/javase/tutorial/essential/io/

38 Basic Concepts: Path  Most operating systems have file directories (folders on your computer), and you can refer to a file by its path.  For example: C:\Pikachu\Moves\thunderbolt.txt  Difference between relative paths and absolute paths  A path is either relative or absolute.  An absolute path always contains the root element and the complete directory list required to locate the file.  Absolute path: C:\Pikachu\Moves\thunderbolt.txt  Relative path: Moves\thunderbolt.txt

39 The Path Class  https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html  An Interface (to be discusses next week)  It is a programmatic representation of a path in the file system  Contains file name, directory list  It allows you to modify, check directories/folders/etc, and access files through it.  Creating a Path: //Microsoft windows Path path = Paths.get("C:\\Users\\Pikachu\\Documents"); //Shorthand for FileSystems.getDefault().getPath(…)

40 40 Try-with-resources  File I/O operations use up system resources. Just like Scanners you used before, you have to close them.  Programmers often forget to close their resources. try-with- resources syntax that automatically closes the resources.  try (declare and create resources) { Use the resource to process the file; }

41 Text File Manipulation: Checking if the File Exists  Checking if it exsists //Verify that the file exists Path path = Paths.get("C:\\Users\\Pickachu\\Documents"); System.out.println(Files.exists(path));  Note: If both exists and notExists return false, the existence of the file cannot be verified.

42 Text File Manipulation: Deleting a File Path path = Paths.get("C:\\Users\\Pickachu\\Documents"); try { Files.delete(path); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); } catch (DirectoryNotEmptyException x) { System.err.format("%s not empty%n", path); } catch (IOException x) { // File permission problems are caught here. System.err.println(x); }

43 Text File Manipulation: Reading a File Line By Line Path path = Paths.get("C:\\Users\\Pickachu\\Documents"); Charset charset = Charset.forName("US-ASCII"); try (BufferedReader reader = Files.newBufferedReader(path, charset)) { String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException x) { System.err.format("IOException: %s%n", x); }

44 Text File Manipulation: Reading All Lines from a File Charset charset = Charset.forName("US-ASCII"); List allLinesInFile = new ArrayList (); try (BufferedReader reader = Files.newBufferedReader(path, charset)) { allLinesInFile = Files.readAllLines(path, charset); } catch (IOException x) { System.err.format("IOException: %s%n", x); }

45 Text File Manipulation: Write to a File Charset charset = Charset.forName("US-ASCII"); String s = "hahaha"; //This opens or creates an existing file try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) { writer.write(s, 0, s.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); }

46 Example: Writing Classroom Information to File


Download ppt "Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA."

Similar presentations


Ads by Google