1 / 33

An Introduction to Java Programming and Object-Oriented Application Development

An Introduction to Java Programming and Object-Oriented Application Development. Chapter 8 Exceptions and Assertions. Objectives. In this chapter you will: Explore how Java throws and catches exceptions Become familiar with many of Java’s exception classes

zola
Download Presentation

An Introduction to Java Programming and Object-Oriented Application Development

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. An Introduction to Java Programming and Object-Oriented Application Development Chapter 8 Exceptions and Assertions

  2. Objectives In this chapter you will: • Explore how Java throws and catches exceptions • Become familiar with many of Java’s exception classes • Take a first look at the concept of inheritance • Write code that handles exceptions thrown by a Java program • Create assertions to debug a program

  3. Exceptions and Assertions • Applications should be robust, or well constructed • Applications should be fault tolerant, or forgiving of user mistakes • Compile-time errors are violations of the programming language syntax • Runtime errors occur during program execution and can cause a program to crash • Logic errors produce incorrect output

  4. Exception Handling • Runtime errors are referred to as exceptions • When Java creates an exception object, it throws the exception for further processing • Two ways to handle exceptions • Do nothing: Let the Java runtime system handle it • Write additional code to handle the exception • Handling the exception is preferable

  5. An Example of a Thrown Exception • The error message produced by Java when an exception is thrown is the stack trace • The method-call stack is the sequence of method calls that leads to creation of exception

  6. An Example of a Thrown Exception (continued)

  7. An Example of a Thrown Exception (continued) • The exception was created in Line 48 of NumberFormatException.java • The method-call stack steps through each call to a method, originating in Line 15 of main • The stack trace gives a complete description of the NumberFormatException object • One option is to add logic to allow the user to enter a greater variety of input

  8. An Example of a Thrown Exception (continued) • When an exception is thrown, the Java runtime system looks for code to handle the exception • The method-call stack is checked for this code • If no such code exists, the exception object is printed and the program terminates • If the exception were handled by the programmer, the code could exit more gracefully • The user could correct mistakes before the program exited

  9. Handling Errors with Program Logic • User input can be checked for validity using additional logic • As programs become more complex, handling errors with additional logic becomes more complicated • Adding logic may make the program less readable • Adding logic may make the program more difficult to maintain

  10. Handling Exceptions with the try Statement • Catching exceptions allows for customized error statements • The user can correct mistakes without restarting the program • The programmer needs three tools • The try block • The catch block • The finally block

  11. Handling Exceptions with the try Statement (continued) • A try block begins with the keyword try • Contains statements where exceptions originate • Contains statements that should normally execute • If an exception occurs, the rest of the try block is skipped • If an exception occurs, program control goes to the first catch block following the try block

  12. Handling Exceptions with the try Statement (continued) • For each try block there is one or more catch blocks • There is one catch block for each type of exception thrown • A catch block begins with the keyword catch and the exception parameter in parentheses • When an exception is thrown, if a catch block matches the exception type, it is executed

  13. Handling Exceptions with the try Statement (continued) • After the catch block is executed, program control continues after the last catch block • An uncaught exception is handled by the Java runtime system • The object’s stack trace is displayed • The program terminates • If no exceptions are thrown, the program skips all catch and finally blocks and processing continues normally

  14. Handling Exceptions with the try Statement (continued) • The finally block is a set of statements that always executes • Useful for tasks like closing files • A try statement is the try, catch and finally blocks • e is the customary identifier for an exception object

  15. Handling Exceptions with the try Statement (continued) • try statement syntax: try { normal program statements } catch (TypeOfException_1 e) { statements to process this exception } … catch (Type of Exception_n e) { statements to process this exception } finally { statements that always execute }

  16. Handling Exceptions with the try Statement (continued) • If a try statement is added to a program, a catch statement must also be added • Each catch statement handles one type of exception • A catch block executes only if an exception of the specified type is thrown within the try block • A finally block can be added immediately after a try block or a combination of try and catch blocks

  17. Classifying Exceptions • Exceptions can be classified according to an inheritance hierarchy • Exceptions can be classified as checked or unchecked • An inheritance hierarchy is like a taxonomy, a classification scheme according to common and unique characteristics • A subclass inherits from the class above it • A superclass is above a subclass

  18. Classifying Exceptions (continued)

  19. Classifying Exceptions (continued) • An unchecked exception inherits from the RuntimeException class • All other exception classes are checked • Checked exceptions cause compiler errors if they are not handled • Unchecked exceptions do not cause compile-time errors, but may cause runtime errors • A throws clause follows the method declaration throwsTypeOfException1,TypeOfException2…

  20. Multiple Catch Blocks and Programmer-Defined Exceptions • The types of exceptions that can be thrown are discovered through extensive testing • catch blocks must immediately follow try blocks with no intervening code • A catch block for a more specific type of exception should precede more general types • Can use an IllegalArgumentException for exception types not previously defined in Java • An Exception object can also be used, but it is poor programming practice

  21. Propagating Exceptions • An exception propagator is a method that originates an exception • An exception catcher is the method that catches the exception • If an exception originates in a method but is not caught, the exception propagates up the method-call stack • The method-call stack is the sequence of method calls

  22. Propagating Exceptions (continued)

  23. Apply the Concept • The application divides two numbers, and is simple to showcase exception handling • A boolean flag thereIsAnError signals that an error or exception has occurred • Three methods are called in a while loop • getDividend • getDivisor • calculateAndDisplay • The while loop executes while thereIsAnError is true

  24. Apply the Concept (continued) • Exceptions are caught if the user terminates the application prematurely • Exceptions are caught if the user enters letters instead of digits • Exceptions originating in getDividend and getDivisor propagate to main • The method calculateAndDisplay catches an IllegalArgumentException if the divisor is zero

  25. Apply the Concept (continued)

  26. Apply the Concept (continued)

  27. Assertions • Three major types of errors • Compile-time errors • Runtime errors • Logic errors • Compile-time errors are the result of syntax errors • Runtime errors cause the program to terminate while running • Logic errors cause incorrect output

  28. Using an Assertion • An assertion is designed to help the programmer detect logic errors • The syntax of an assert statement: assertexpression:error message • The expression is a boolean expression that should always be true if the program is working • The error message is displayed if the expression ever becomes false • Assertions are placed after all values in expression have been determined

  29. An Example of an Assertion • An assert statement is placed to verify that kilograms are less than pounds • If the assertion is false, an AssertionError is thrown • The custom error is optional, but useful • Compile with the –source1.5 option • Run with assertions enabled: -ea

  30. An Example of an Assertion (continued)

  31. Summary • Programs can be made more robust and fault tolerant using exception handling • Exceptions are handled using a try statement • The try statement consists of a try block, a catch block, and an optional finally block • Exceptions can be classified according to the inheritance hierarchy, or as checked or unchecked • The inheritance hierarchy is a taxonomy of Java classes

  32. Summary (continued) • A subclass inherits from the class just above it • The superclass is the class just above a given class in the hierarchy • Unchecked exceptions inherit from the RuntimeException class • All other exceptions are checked • Checked exceptions must be handled or the program will not compile

  33. Summary (continued) • Must be one catch block for every try block • Each catch block handles one type of exception • Multiple catch blocks may follow a try block • Exceptions that are not caught are propagated up the method-call stack • An assertion can be used to guarantee that programmers don’t make major logic errors

More Related