1 / 18

Introduction

Introduction. Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation Correct use of exception handling Benefits of exception handling Summary. Errors. The Golden Rule of Programming: Errors occur in software programs!

stesha
Download Presentation

Introduction

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. Introduction • Errors • Exceptions in Java • Handling exceptions • The Try-Catch-Finally mechanism • Example code • Exception propagation • Correct use of exception handling • Benefits of exception handling • Summary

  2. Errors • The Golden Rule of Programming: • Errors occur in software programs! • How do we deal with errors? • Try to minimise their occurrence (bug-checking). • Prevent invalid data from entering the system (validation). • Handling errors as they occur (exception handling). • Exception handling is a coding mechanism which handles errors as they occur and prevents the program from crashing

  3. Exceptions • Definition:  An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. • What kinds of exceptions can occur in Java? • Input/Output exceptions • Memory exceptions • Mathematical exceptions • Pointer exceptions, and many more... • When an exception occurs it is said that the exception has been ‘thrown’.

  4. Checked and Unchecked • Unchecked exceptions are the type of exceptions we don't want to have to catch. • For example: nAverage = nSum/nTotalUsers; • Can generate a divide-by-zero exception! • We don't put try/catch round every bit of maths. • Checked exceptions are the ones we do need to catch and process. • For example we may need to give feedback to a user to remind them to put a CD into a drive or to add paper to a printer.

  5. Handling Exceptions • The mechanism for handling exceptions during program execution is the Try-Catch-Finally block. • The general format for using these statements is: try { // some Java code that can cause an exception } catch(exception thrown) { // code to handle the exception } finally {// tidy up code (optional) }

  6. The Try Block • The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. • In general, a try block looks like this: try { Java statements } • The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an exception.

  7. The Catch Block • The try statement defines the scope of the exceptions which might be thrown. • You provide one or more catch blocks directly after the try block: [why multiple catch blocks?] try { . . . } catch ( . . . ) { . . . } catch ( . . . ) { . . . }

  8. The Finally Block • The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before (possibly) allowing control to be passed to a different part of the program. • You do this by enclosing the cleanup code within a finally block. • The finally block comes in useful when a piece of code must be executed regardless of whether the try block was successful or not. • e.g. closing a File object.

  9. File Example • try • { BufferedReader br = new BufferedReader(newFileReader("MyFile.txt"));String line = br.readLine(); • } • catch(FileNotFoundException fnfe) • { System.out.println("File MyFile.txt not found."); • } • catch(IOException ioe) • { System.out.println("Unable to read from MyFile.txt"); • } • return line;

  10. File Example • The constructor of FileReader throws a FileNotFoundException (a subclass of IOException) if the specified file is not found. • Otherwise, if the file exists but for some reason the readLine() method can't read from it FileReader throws an IOException. • (maybe the file has user access privileges or is currently locked by another user)

  11. Propagation of Exceptions • You can decide to not deal with an exception within a particular method, • Then you must declare that the method can throw exceptions. • These exceptions are then passed up the chain of calling methods. • e.g. if some part of your sub-system produces an exception but you want your user-interface classes to deal with it then you can. • All intervening methods must have their signatures set to throw the exception(s).

  12. Method Signatures • A try-catch block must then be placed around the call to the top-level intervening method. • If you are going to propagate an exception from a method then the method signature has to specify this. public String readHeader() throws FileNotFoundException, IOException { // method code }

  13. Example • method1 • { try { call method2; } • catch (exception) { doErrorProcessing; } • } • method2 throws exception • { call method3; • } • method3 throws exception • { call readFile; • }

  14. Correct Use • Often, developers add the mechanism as an afterthought. • Significant re-engineering during the coding stage can make this oversight an expensive proposition. • A clear and detailed exception-handling strategy pays off in the form of robust code, which in turn, enhances user value.

  15. Benefits • Java's exception-handling mechanism offers the following benefits: • It separates the working/functional code from the error-handling code by way of try-catch clauses. • It allows a clean path for error propagation. If the called method encounters a situation it can't manage, it can throw an exception and let the calling method deal with it.

  16. Benefits • Java's exception-handling mechanism offers the following benefits: • By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding. • Forcing the developer to code for exceptions improves the quality of information for users of the code – compare with C++ where exceptions are “unchecked” and often undocumented.

  17. Problems with Exceptions • It can be hard to propagate exceptions at the appropriate level of abstraction, for example; • A “SQLException” at one level could be a “DuplicateUserIDException” elsewhere. • Sometimes handling exceptions properly is a lot of work for extremely rare cases. • Lazy developers can easily avoid handling exceptions properly – and often do.

  18. Summary • Errors can always occur. • By using the exception handling mechanism, you can let your code deal with the error and continue execution. • The exception handling mechanism separates your code from the code which deals with the error. • This can be code that is placed further up the method call stack. • Use of the exception handling mechanism leads to robust applications that users can feel confident with.

More Related