7.7. Review notes

This section lists the main points of all the sections covered in this chapter.

Why handle exceptions separately:

  • Handling exceptions separately enables you to define the main logic of your code together.
  • Without the use of separate exception handlers, the main logic of your code would be lost in combating the exceptional conditions. (See figure 7.5 for an example.)
  • Exception handlers separate the concerns of defining regular program logic from exception-handling code.
  • Exceptions help pinpoint the offending code, together with the method in which it’s defined, by providing a stack trace of the exception or error.
  • The JVM may send the stack trace of an unhandled exception to the Java console.

Categories of exceptions:

  • Exceptions are divided into three categories: checked exceptions, runtime (or unchecked exceptions), and errors. These three categories share IS-A relationships (inheritance).
  • Subclasses of the class java.lang.RuntimeException are categorized as runtime exceptions.
  • Subclasses of the class java.lang.Error are categorized as errors.
  • Subclasses of the class java.lang.Exception are categorized as checked exceptions if they’re not subclasses of the class java.lang.RuntimeException.
  • The class java.lang.RuntimeException is a subclass of the class java.lang.Exception.
  • The class java.lang.Exception is a subclass of the class java.lang.Throwable.
  • The class java.lang.Error is also a subclass of the class java.lang.Throwable.
  • The class java.lang.Throwable inherits the class java.lang.Object.

Checked exceptions:

  • A checked exception is an unacceptable condition foreseen by the author of a method but outside the immediate control of the code.
  • A checked exception is a subclass of the java.lang.Exception class but not a subclass of java.lang.RuntimeException. It’s interesting to note, however, that the class java.lang.RuntimeException itself is a subclass of the class java.lang.Exception.
  • If a method calls another method that may throw a checked exception, either it must be enclosed within a try-catch block, or the method should declare this exception to be thrown in its method signature.

Runtime exceptions:

  • Runtime exceptions represent programming errors. These occur from inappropriate use of another piece of code. For example, NullPointerException is a runtime exception that occurs when a piece of code tries to execute some code on a variable that hasn’t been assigned an object and points to null. Another example is ArrayIndexOutOfBoundsException, which is thrown when a piece of code tries to access an array of list elements at a nonexistent position.
  • A runtime exception is a subclass of java.lang.RuntimeException.
  • A runtime exception might not be a part of the method signature, even if a method may throw it.
  • A runtime exception may not necessarily be caught by a try-catch block.

Errors:

  • An error is a serious exception, thrown by the JVM as a result of an error in the environment state, which processes your code. For example, NoClassDefFoundError is an error thrown by the JVM when it’s unable to locate the .class file it’s supposed to run.
  • StackOverflowError is another error, thrown by the JVM when the size of the memory required by the stack of the Java program is greater than what the JRE has offered for the Java application. This error usually occurs as a result of infinite or highly nested loops.
  • An error is a subclass of the class java.lang.Error.
  • An error need not be a part of a method signature.
  • Although you can handle errors syntactically, there’s little that you can do when these errors occur. Usually, ordinary programs aren’t expected to recover from errors.

Creating a method that throws an exception:

  • A method uses a throw statement to throw an exception or error.
  • A method uses a throws clause in its signature to declare that it might throw an exception.
  • A method can have multiple comma-separated class names of exceptions in its throws clause. Including runtime exceptions or errors in the method declaration isn’t required.
  • Syntactically, you don’t always need a combination of throw and throws statements to create a method that throws an exception (checked or unchecked). You can replace the throw statement with a method that throws an exception.
  • To use a method that throws a checked exception, you must do one of the following:

    • Handle the exception—Enclose the code within a try block and catch the thrown exception.
    • Declare it to be thrown—Declare the exception to be thrown by using the throws clause.
    • Handle and declare—Implement both of the preceding options together.
  • While creating a method that throws a runtime exception or error, including the exception or error name in the throws clause isn’t required.
  • A method that throws a runtime exception or error isn’t subject to the handle-or-declare rule.
  • A method can declare to throw all types of exceptions, even if it doesn’t. But a try block can’t define a catch block for a checked exception (other than Exception) if the try block doesn’t throw that checked exception or use a method that declares to throw that checked exception.

What happens when an exception is thrown:

  • An exception is an object of the class java.lang.Throwable.
  • When a piece of code hits an obstacle in the form of an exceptional condition, it creates an object of subclass java.lang.Throwable, initializes it with the necessary information (such as its type and optionally a textual description and the offending program’s state), and hands it over to the JVM.
  • Enclose the code that may throw an exception within a try block.
  • Define catch blocks to include alternative code to execute when an exceptional condition arises.
  • A try block can be followed by one or more catch blocks.
  • The catch blocks must be followed by zero or one finally block.
  • The finally block executes regardless of whether the code in the try block throws an exception.
  • The order in which the catch blocks are placed matters. If the caught exceptions have an inheritance relationship, the base class exceptions can’t be caught before the derived class exceptions. An attempt to do this will result in compilation failure.
  • A finally block will execute even if a try or catch block defines a return statement.
  • If both catch and finally blocks define return statements, the calling method will receive the value from the finally block.
  • If a catch block returns a primitive data type, a finally block can’t modify the value being returned by it.
  • If a catch block returns an object, a finally block can modify the value being returned by it.
  • A finally block alone won’t suffice with a try block if code in the try block throws a checked exception. In this case, you’ll need to catch the checked exception or define in the method signature that the exception is thrown, or your code won’t compile.
  • None of the try, catch, and finally blocks can exist independently.
  • The finally block can’t appear before a catch block.
  • You can rethrow an error that you catch in an exception handler.
  • You can either handle an exception or declare it to be thrown by your method. In the latter case, you need not handle the exception in your code. This applies to checked exceptions.
  • You can create nested exception handlers.
  • A try, catch, or finally block can define another try-catch-finally block. Theoretically, there’s no limit on the allowed level of nesting of try-catch-finally blocks.

Commonly occurring exceptions, categories, and classes:

  • In typical programming conditions, the ArrayIndexOutOfBoundsException shouldn’t be thrown programmatically.
  • One of the main reasons for the JVM taking the responsibility on itself for throwing this exception is that this exception isn’t known until runtime and depends on the array or list position that’s being accessed by a piece of code. Most often, a variable is used to specify this array or list position, and its value may not be known until runtime.
  • ClassCastException is a runtime exception. java.lang.ClassCastException extends java.lang.RuntimeException.
  • ClassCastException is thrown when an object fails an IS-A test with the class type it is being cast to.
  • You can use the operator instanceof to verify whether an object can be cast to another class before casting it.
  • IllegalArgumentException is a runtime exception. java.lang.Illegal-Argument-Exception extends java.lang.RuntimeException.
  • An IllegalArgumentException is thrown to specify that a method has been passed illegal or inappropriate arguments.
  • Even though IllegalArgumentException is a runtime exception, programmers usually use this exception to validate the arguments that are passed to a method, and the exception constructor is passed a descriptive message specifying the exception details.
  • As a programmer, you can throw an IllegalStateException to signal to the calling method that the method that’s being requested for execution isn’t ready to start its execution or is in a state in which it can’t execute.
  • A NullPointerException is a runtime exception. The class java.lang.NullPointerException extends java.lang.RuntimeException.
  • A NullPointerException is thrown by the JVM if you try to access a method or variable of an uninitialized reference variable.
  • When the JVM encounters an exceptional mathematical condition, like dividing a number by zero, it throws an ArithmeticException.
  • In division with integers, if the divisor is 0, the integer value that’s being divided doesn’t matter. Such an operation will throw an ArithmeticException.
  • Division of a negative or positive integer value by 0 will result in an Arithmetic-Exception.
  • Division of 0 by 0 results in an ArithmeticException.
  • If you divide a positive decimal value by 0, the result is Infinity. If you divide a negative decimal value by 0, the result is -Infinity.
  • Division of 0.0 by 0 results in NaN (Not a Number).
  • When a positive integer or decimal value is divided by 0.0, the result is Infinity.
  • When a negative integer or decimal value is divided by 0.0, the result is –Infinity.
  • NumberFormatException is a runtime exception. java.lang.NumberFormat-Exception extends java.lang.IllegalArgumentException. java.lang.IllegalArgumentException extends java.lang.RuntimeException.
  • You can throw a NumberFormatException from your own method to indicate that there’s an issue with the conversion of a String value to a specified numeric format (decimal, octal, hexadecimal, or binary).
  • Runtime exceptions arising from any of the following may throw an ExceptionInInitializerError:

    • Execution of an anonymous static block
    • Initialization of a static variable
    • Execution of a static method (called from either of the previous two items)
  • The error ExceptionInInitializerError can be thrown only by an object of a runtime exception.
  • ExceptionInInitializerError can’t be thrown if a static initializer block throws an object of a checked exception, because the Java compiler is intelligent enough to determine this condition, and it doesn’t allow you to throw an unhandled checked exception from a static initialization block.
  • StackOverflowError is an error. java.lang.StackOverflowError extends java.lang.VirtualMachineError.
  • Because StackOverflowError extends VirtualMachineError, it should be left to be managed by the JVM.
  • The StackOverflowError error is thrown by the JVM when a Java program calls itself so many times that the memory stack allocated to execute the Java program “overflows.”
  • NoClassDefFoundError is an Error. java.lang.NoClassDefFoundError extends java.lang.LinkageError. java.lang.LinkageError extends java.lang.Error.
  • A NoClassDefFoundError is thrown by the JVM or a ClassLoader when it’s unable to load the definition of a class required to create an object of the class.
  • Don’t confuse the exception thrown by Class.forName(), used to load the class, and NoClassDefFoundError, thrown by the JVM. Class.forName() throws a ClassNotFoundException.
  • An OutOfMemoryError is thrown by the JVM when it’s unable to create objects on the heap and the garbage collector may not be able to free more memory for the JVM.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.197.213