1 / 38

Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

Chapter 10: Exceptions and Advanced File I/O. Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260. Chapter Topics. Chapter 10 discusses the following main topics: Handling Exceptions Throwing Exceptions Getting Current Date and Time

york
Download Presentation

Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10:Exceptions and Advanced File I/O Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

  2. Chapter Topics Chapter 10 discusses the following main topics: • Handling Exceptions • Throwing Exceptions • Getting Current Date and Time • More about Java Packages • More about Input/Output Streams • Advanced Topics: • Binary Files, • Random Access Files, and • Object Serialization Not covered in class

  3. Dealing with Error Situations • There are 3 major categories of errors with which we must deal: • Compile-time errors – mostly involving Java syntax errors (missing semicolon, misspelled name, missing import, etc.) • Eclipse helps us out with these, giving squiggly lines, messages, tool-tips, and other information about the errors and, often, suggestions about what to do to correct them • Run-time errors – the program crashes as it is running • This chapter is mostly about dealing with this type of error. • Logic Error – the program compiles and runs, but some or all of the results are incorrect • Often the hardest errors to discover and correct because one has to test the program thoroughly even to know that there are flaws • Just because a program has no syntax errors and runs without crashing does not mean the results it produces are correct. • Test, test, test, test, test, test!

  4. Handling Exceptions • An exception is an object that is generated as the result of an error or other unexpected event. • Exceptions are said to “thrown.” • It is the programmer’sresponsibility to write code that detects and handles exceptions. • Java allows you to create exceptionhandlers – pieces of code that execute only if an exception has occurred. • Unhandledexceptions will crash a program. • If an exception occurs and there is no handler to deal with the exception, the program crashes. • It displays a message and the program is terminated. • Example: BadArray.java – see next slide

  5. Runtime Error Example Loop goes too far. Array has 3 items with subscripts 0, 1, and 2. This loop tries to access item in subscript position 3 – then it crashes The program worked correctly for subscripts 0, 1, and 2, but crashed for subscript 3 Line number where error was detected

  6. Handling Exceptions • An exceptionhandleris a section of Java code that gracefully responds to exceptions. • “Gracefully” means that the program deals with the exception in some rational way without simply “crashing” the program • It might try to correct the problem and continue • It might display a message alerting the user to take a corrective action • It might save all the information, display a clear message, and terminate the program “normally.” • And so forth … • The process of intercepting and respondingtoexceptions is called exceptionhandling. • A defaultexceptionhandleris provided by Java to deal with exceptions that occur but that the program does not handle. • The default exception handler displays an error message and crashes the program. • See previous slide for an example of Java’s default exception handler at work.

  7. Exception Classes • An exception is an object. • Exception objects are created from classes in the JavaAPIhierarchy of exceptionclasses. • All of the exception classes in the hierarchy are derived from the Throwable class. • Error and Exception are derived from the Throwable class.

  8. Exception Classes • Classes that are derived from Error are for exceptions that are thrown when critical errors occur. Examples of these are • An internal error in the Java Virtual Machine • Running out of memory • Applications should not try to handle these errors because they are the result of serious conditions that are beyond the ability of application programs to handle • Programmers should handle the exceptions that are instances of classes that are derived from the Exception class

  9. Exception Classes Object Throwable Error Exception … … IOException RuntimeException … EOFException FileNotFoundException … More info available at http://java.sun.com/javase/6/docs/api/

  10. Handling Exceptions • To handle an exception, you use a trystatement. try { (try block statements go here ...) } catch (ExceptionType ParameterName) { (catch block statements go here ...) } • The keyword try indicates a block of code will be attempted (the curly braces are required) and monitored for possible exceptions • This block of code is known as a tryblock. • Note that this is not necessarily an indication of a lack of confidence in the correctness of our code – there are many reasons that correct code can encounter exceptional conditions such as • Bad input from user (garbage in, garbage out) • Out of memory • Disk, CD, or thumb drive is full, read-only, or offline • Hardware failure or network problem • Security issue blocking necessary access • And many others …

  11. Handling Exceptions • A try blockcontains: • One or more statements that are to be executed • Some of the statements can potentially result in an exception being thrown • The application will not automatically halt if the try block throws an exception – because the application may intercept it and deal with it • If code that is not in a tryblock throws an exception: • The program cannot intercept it and handle it • The system takes a standard action – usually crashes the program • After the try block, a catch block appears

  12. Handling Exceptions • A catch clause begins with the key word catch: catch (ExceptionType ExceptionObjectName) • ExceptionTypeis the name of an exception class and • ExceptionObjectNameis a variable name that will reference the exception object if the code in the try block throws an exception • This is similar to a method’s parameter, but • There may be onlyone parameter • It must be of some Exception type • The code that immediately follows the catch clause is known as a catchblock(the curly braces are required) • The code in the catchblock is executed if and only if the tryblockthrows an exception

  13. Handling Exceptions - example • This code handles a FileNotFoundException if it is thrown - it simply displays a message and then continues with the program. try { File file = new File ("MyFile.txt"); Scanner inputFile = new Scanner(file); } catch (FileNotFoundException e) { System.out.println("File not found."); } • The Java Virtual Machine searches for a catch clause that can deal with the exception. • Example: OpenFile.java

  14. Handling Exceptions • The parameter for a catch block must be of a type that is compatible with the thrownexception’s type. • Otherwise, the catchhandler will notcatch itwhenitisthrown • After an exceptionishandled, the program will continue execution at the point just past the catch block • Note that control does NOT return to pointoftheexception • If, after handling the exception, you wish to retry the tryblock, you must put it in a loop such as a whileloop • If no exception is thrown, execution skips the catchblock completelyand continuesafter the catch block.

  15. Example

  16. Handling Exceptions • Each type of exception class has a message field that allows one to store a message in the exceptionobject that is thrown • For standard exception classes in Java, there is a default message • The message gives some information about the reason the exception was thrown • Each exception object has a method named getMessage that can be used to retrieve the errormessage associated with that exception. • Example: • ExceptionMessage.java • ParseIntError.java

  17. Example: ParseIntError

  18. Polymorphic References To Exceptions • Most exceptions thrown are objects of classes derived from the Exception class. • Therefore, when handling exceptions, you can use a polymorphic reference as a parameter in the catch clause (using the is-a relationship provided by the inheritance mechanism in Java) • A catch clause that uses a parameter variable of the Exception type can catch any thrownexception derived from the Exception class

  19. Polymorphic References To Exceptions try { number = Integer.parseInt(str); } catch (Exception e) { System.out.println("The following error occurred: " + e.getMessage()); } • The Integer class’s parseInt method throws a NumberFormatException object if the argument cannot be converted to an integer (for example, if str = “Samantha”;) • The NumberFormatException class is derived from the Exception class. • Thus, this catchhandler can catch it, making life easier • One doesn’t have to know the specific type of exception that might be thrown • If a tryblock might throw one of several different exceptions, one catchhandler might be able to handle all of them

  20. Handling Multiple Exceptions • The code in the try block may be capable of throwing more than one type of exception. • A separate catch clause may to be written for each type of exception that could potentially be thrown if different actions are required to handle each different type of exception • The JVM will run only the first compatible catch clause found. • The catch clauses must be listed from mostspecific to mostgeneral. • Example: SalesReport.java, SalesReport2.java

  21. Exception Handlers • There can be many polymorphic catch clauses. • A try statement may have only onecatch clause for each specific individual type of exception. try { number = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Bad number format."); } catch (NumberFormatException e)// ERROR!!! { System.out.println(str + " is not a number."); } Error to have a second handler for the same type of exception – we could never reach it anyway since the first catch would have handled the exception

  22. Exception Handlers • The NumberFormatException class is derived from the IllegalArgumentException class. • The following is not valid because the first catch handler would catch everything the second handler could catch. • The more general handler is given before the more specific handler – WRONG!!! try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) { System.out.println("Bad number format."); } catch (NumberFormatException e)// ERROR!!! { System.out.println(str + " is not a number."); }

  23. Exception Handlers • The previous code could be rewritten to work, as follows, without errors, by placing the most specific typefirst and the more generic type after it. try { number = Integer.parseInt(str); } catch (NumberFormatException e) //More specific type { System.out.println(str + " is not a number."); } catch (IllegalArgumentException e)//OK–parent class { System.out.println("Bad number format."); }

  24. The finally Clause • Sometimes, one needs to take some specific action(s) regardless of whether an exception was thrown • Examples • If a file has been opened, it should be closed before the program ends regardless of whether an exception was thrown in the meantime • If data has been calculated, before ending the program, one may need to saveit to a file or a database whether or not an exception has been thrown subsequently • If one has connected to a network or a database or some other resource that is no longer needed, it may be necessary to disconnect regardless of whether an exception has been thrown

  25. The finally Clause • For this purpose, a finally clause may be used with a try/catch. • Thefinally clause is optional. It is only used if it is needed to specify an action that should be done whether an exception was thrown on not. • If present, the finally clause must appear after the last catch clause. try { (try block statements...) } catch (ExceptionType ParameterName) { (catch block statements...) } finally { (finally block statements...) }

  26. The finally Clause • The finally blockcontains one or more statements • These statements are always executed after the try block has executed and • After a catch block was executed if anexception was thrown • The statements in the finally block execute whether an exception occurs or not.

  27. The Stack Trace • When a Java program is executing, the system tracks the execution history • For example, if method m1 invokes method m2, the system has to remember where it was in m1 so that when m2 finishes and returns, the system knows where to return. • If a program crashes, the execution history not only tells you where you were in the program when it crashed but also how you got there • The latter is important because a method might be invoked from many different places in a program and knowing which invocation caused the crash may help you find and correct the problem • The executionhistory is called the stacktrace

  28. The Stack Trace • The call stackis an internal list of all the methods that are currently executing. • A stacktraceis a list of all the methods in the call stack. • Reviewing the stack trace when an exception occurs allows one to determine • the method that was executing when the exceptionoccurred and • all of the methods that were called in order to get to that method • A stack trace may be shown by Java’s default exception handler when an unhandled exception occurs • From a catch block, one may display a stack trace without involving Java’s default exception handler. If e is the exception object, to display the stack trace, use e.printStackTrace ( ); • Example: StackTrace.java

  29. Uncaught Exceptions • When an exception is thrown, it cannot be ignored. • It must be handled by the program, or it will be handled bythedefault exception handler. • When the code in a method throwsanexception: • normal execution of that method stops, and • the JVM searches for a compatibleexceptionhandlerinside the method. • Continued on next slide …

  30. Uncaught Exceptions • If there is no matching exception handler inside the method: • control of the program is passed back to the previousmethod in the callstack – that is, to the invoking method • If that method has nomatchingexception handler, then control is passed again, up thecallstack, to the previous method – the method that invoked it • If control reaches the main method: • the main method must either handletheexception, or • the programishalted and the defaultexceptionhandler for Java handles the exception

  31. Throwing your own exceptions • If you detect an exceptional condition, you may throw your own exception • It may be an exception object of one of the Java exception types • It may also be an exception object of a type that you create • For example if (num > 0) average = total / num; else throw new Exception(“Cannot divide by 0”);

  32. Throwing Exceptions • You can write code that throws an instance of: • one of the standard Java exceptions • a custom exception class that you have designed • The throw statement is used to manually throw an exception. throw new ExceptionType(MessageString); • The throw statement causes an exception object to be created and thrown. • The MessageString parameter is the value assigned to the message field of the exception object.

  33. Throwing Exceptions • The MessageStringargument contains a custom error message that can be retrieved from the exception object’s getMessage method. • If you do not pass a message to the constructor, the exception will have a null message. throw new Exception(“Dose too high – patient dead"); • Note: Don’t confuse the throw statement with the throws clause. • Examples: • InventoryItem.java, InventoryDemo.java

  34. Creating Exception Classes • You can create your own exception classes by deriving them from the Exception class or one of its derived classes. • Example: • BankAccount.java, NegativeStartingBalance.java, AccountTest.java Derived from Exception Base-classconstructor sets message

  35. The Current Date and Time • To get and format the current date for display use code similar to the following Must import these two classes Output produced

  36. Current Date and Time • Dealing with the current time is similar

  37. Creating your own named Java packages • A package is a collection of relatedclasses • You may create your own and not always use the “defaultpackage” in Eclipse

  38. Your own packages • Once the package is created, you may add classes to it in the same way you would for the defaultpackage in previous exercises • To use this package in anotherprojector in anotherpackage in the sameproject, you must import it: import myUtilityClasses;

More Related