Chapter 12
Exception Handling

Student Learning Outcomes
Learn about exceptions
2. Try code and catch exceptions
3. Throw and catch multiple exceptions
4. Use the finally block
5. Understand the advantages of exception handling
6. Specify the Exceptions a method can throw
7. Trace Exceptions though the call stack
8. Create you own exceptions
9. Use an assertion

Important Points
1. An exception is an unexpected or error condition.  i.e. A file doesn't exist when you try to read it, or no space on disk when writing to disk, user puts in wrong data, divide by 0, or reading an array whose subscript is too short or too long.
a. Exception handling is the name for the OOP techniques to manage such errors.
b. Runtime exception occurs during a program’s execution and are built in to Java.
c. Java acknowledges more than 75 categories of exceptions such as ActivationException, AlreadyBoundException. etc.
IOException, RuntimeException, ArithmeticExceptionIndexOutOfBoundsException, ArrayIndexOutOfBoundsException, NoSuchElementException, InputMismatchException
, are a few.
d. The Error class represents more serious errors from which your program usually cannot recover.
e. An Exception class comprises less serious errors that represent unusual conditions that arise while a program is running and can recover.
f. An Exception message is displayed when the program code could have prevented an error.
g. A stack trace or stack trace history list is a list of error messages after each attempted execution.
h. Mission critical refers to any process that is crucial to an organization.
i. Fault tolerant applications are designed so that they continue to operate.
j. Robustness represents the degree to which a system is resilient to stress, maintaining correct functioning.

2. Try code and catch exceptions.
  A try block is a block of code you attempt to execute while acknowledging that an exception might occur.
a. The keyword is
try, an opening curly brace, executable statements including some that might cause exceptions, a closing curly brace.
b. A
catch block is a segment of code that can handle an exception that might be thrown by the try. Includes the keyword catch, an opening parenthesis, an exception type, a name for an instance of the exception type, a closing parenthesis, an opening curly brace, statements that take the action you want to use to handle the error condition, and a closing curly brace.
c. You usually code a least one
catch block immediately following a try block to handle an exception that might be thrown by the try block.
d. If you do not include a
catch block immediately after a try block, then you must code a finally block.
e. A
throw statement is one that sends an exception out of a block or a method so it can be handled elsewhere.
f. Example:

     //statement or statements that might generate an exception   
catch(exception someException)   //here enclosed in () we can type the type of exception and the name we give it.
     //actions to take if exception occurs

g. One can also add code to a catch block to correct the error.
h. Example:

catch(ArithmeticException mistake)
        system.out.println(mistake.getMessage());  //this calls the ArithmeticException class using the getMessage() from the class
returns   // by zero

3. Throwing and Catching Multiple Exceptions. You can put many statements in the
try block, but the first one that has an exception is the only one dealt with in the catch. If other statements follow the exception they will not be executed. When a program contains multiple catch blocks they are examined in sequence until a match is found for the type of exception that occurred. Only that catch will be executed, the others will be ignored.
a. Since the ArithmeticException and the InputMismatchException are sub classes of Exception class, the following code would catch both types of errors.

catch(Exception mistake)
     system.out.println("Operation unsuccessful");

b. As soon as an exception occurs, the try block that contain it is abandoned and the rest of its statements are unexecuted.
c. When a program contains multiple catch blocks, the first one that matches the thrown exception type is the one that executes.

4. Using the finally block.
  When you have actions you must perform at the end of a try...catch, you can use a finally block.
a. The try…catch…finally format

     // statements to try
catch(Exception e)
     // actions that occur if exception was thrown
     // actions that occur whether catch block executed or not

b. The code within a finally block executes regardless of whether the preceding try block identifies an exception. Use to perform cleanup tasks that must happen whether or not any exceptions occurred or where caught. The finally block might not execute if an unplanned exception occurs or the try or catch might contain a System.exit() statement.
c. The superior approach is to
try all the statements that might throw an exception and include all the needed catch blocks and the optional finally block.
d. An uncaught exception causes the method to abandon prematurely. An uncaught exception does not allow the
try block to finish, nor does it cause the catch block to execute.
e. If a
try block calls the System.exit() method and the finally block calls the same method, the finally block method is used and the try ignored.

5. Understanding the Advantages of Exception Handling.  In OOP exception handling is flexible, it allows in the handling of error situations. In many cases you want the method to check for errors but not want it to handle the exception. In OOP you gain the ability to appropriately deal with exceptions.

6. Specifying the Exceptions a Method can throw.
If a method throws an exception that it will not catch, but that will be caught by a different method, you must have the keyword
throws followed by the exception type in the method header. Known as an exception specification.
a. Example:

public static void displayPrice(int item) throws IndexOutOfBoundsException.

b. The only exceptions that must be caught or named in a throws clause are the types known as checked exceptions.
c. Unchecked exceptions - inherit from the error class or the runtime exception class. Although you can handle these exceptions in your program, you are not required to do so.
d. Checked exceptions - type that programmers should anticipate and from which programs should be able to recover. All exceptions that you explicitly throw and that descend from the exception class are checked exceptions.
e. Checked exceptions are subject to the
catch or specify requirement which means you must
    -Catch it within the method or
    -Specify the exception in your method header’s
throws clause.
f. Code that uses a checked exception will not compile if the
catch or specify rule is not followed.
g. If you write a method with a
throws clause in the header, then any method that uses the method must do one of the following:
Catch and handle the possible exception or
    -Declare the exception in its
throws clause. The called method can then rethrow the exception to yet another method that might either catch it or throw it yet again.
h. Many exceptions never have to be explicitly thrown or caught. Java compiler does not require that you catch or specify runtime exceptions.

7. Tracing exceptions through the call stack. 
A call stack is where the computer stores the list of method locations to which the system must return after each method call.
a. If Method A calls Method B, and Method B calls Method C, and Method C has an exception that is not caught then it goes to back to Method B to catch the exception, if Method B cannot catch the exception it goes back to method A to catch it, if not then to the operating system. 
b. When a program uses several classes, the programmer finds it difficult to locate the original source of an Exception.
c. The
printStackTrace() method displays a list of methods in the call stack so you can determine the location of the exception.
d. Usually, you do not place a
printStackTrace() method call in a finished program. It is useful tool for diagnosing your class's problems while you are developing an application.

8. Creating your own exceptions:
Java provides over 40 categories of exceptions but could not predict all exceptions.
a. To create your own
throwable exception you must extend a subclass of Throwable. Throwable has two subclasses. Exception (recoverable errors) and error.
b. Most programmer-created exceptions are extended from the exception class, which has four constructors




Constructs a new exception with null as its detail message

Exception(String message)

constructs a new exception with the specified detail message

Exception(String message, Throwable cause)

Constructs a new exception with the specified detail message and cause

Exception(Throwable cause)

Constructs a new exception with the specified cause and a detail message of cause.toString(), which typically contains the class and the detail message of cause, or null if the cause argument is null

9. Using Assertions:
Assertion is a Java language feature that can help you detect logic errors and debug a program. An assert statement is use to create an assertion. You state a condition that should be true and Java throws an assertionError when it is not.
assert booleanExpression : optionalErrorMessage  example: assert number % 2==0: number + " 2 is " + number % 2;
b. To enable an assertion you must use the -ea when you execute the program. If it is not used, the assertions are ignored during program execution.
c. The Boolean expression in an assert statement should always be true if the program is working correctly.
d. Helps reduce debugging time and are used primarily during the development stage.