2. Exceptions
• Events that disrupt the normal flow of
execution.
• Exception Object
1) cause (can contain another exception),
2) detailed message.
• Can be thrown by the programmer using the
throw keyword.
• Can be caught by the programmer using the
catch keyword.
3. Benefits of Java Exception Handling
• Cleaner code by separating error handling
code from normal or happy path code.
• Propagate errors up the call stack where they
can be handled meaningfully.
• Helps to categorize exceptions using the
exception hierarchy.
4. Types of Errors
• JVM Errors => OutOfMemoryError,
StackOverflowError, LinkageError
• System Errors => FileNotFoundException,
IOException, NullPointerException,
ArrayIndexOutOfBoundsException
• Application Errors => InsufficientFundsException
(transfer balance from one account to another).
• JVM & System Errors are built-in, Application
Errors are user defined.
5.
6. Exception Handling – try, catch, finally
• Try block – normal flow of execution.
• Catch blocks ( 1 or more) – exception handling
code, are like if-else-if statements – only 1 can
potentially execute.
• Derived class exception should be caught
before a base class exception in the catch
blocks.
• If an exception is thrown that is not handled,
it is propagated up the call stack.
7. Finally Block
• Finally block – clean up code, always gets
executed, even when you have a return in
try/catch or any exception is re-thrown.
• When does finally not execute ? – It may not
execute when JVM terminates (via
System.exit()) or current thread is killed or
system runs out of memory.
• If an exception is thrown that is not handled,
it is propagated up the call stack.
8. Checked & Unchecked Exceptions
• Checked – compiler forces you to either catch
them or declare in the throws clause. Use it
for recoverable errors.
• Unchecked – RuntimeException and its
subclasses are unchecked exceptions. Compiler
does not force you to catch them. Unchecked
exceptions do not need to be declared in a
method’s throws clause.
9. Error
• An Error is a subclass of Throwable that indicates serious
problems that a reasonable application should not try to
catch.
• Most such errors are abnormal conditions that should
never occur.
• A method is not required to declare in its throws clause any
subclasses of Error that might be thrown during the
execution of the method but not caught.
• Error and its subclasses are regarded as unchecked
exceptions for the purposes of compile-time checking of
exceptions.
• Examples: OutOfMemoryError, VirtualMachineError,
AssertionError, IOError.
10. User Defined Exceptions
• These are business or application exceptions.
• Class Name ends with the string Exception.
Examples: InsufficientFundsException,
AccountClosedException.
• If user defined exception is a checked
exception, it should extend Exception,
otherwise it should extend RuntimeException.
• Add custom fields and getters/setters to store
more information.
11. Nesting Exceptions
• An exception can nest or contain another
exception.
• Many APIs throw a generic exception which
contain the implementation exception.
• Example: Spring Framework
DataAccessException nests the JDBC
SQLException.
• SomeApiException.getCause() retrieves the
implementation exception.
12. Recommendations – part 1
• Use exceptions only for exceptional conditions.
• Close or release resources in the finally block.
• Use checked exceptions for recoverable errors.
• Runtime exceptions indicate programming errors - do not catch
them.
• Errors are unchecked exceptions – generally should not be caught.
• Catch exceptions only where you can handle them meaningfully,
otherwise re-throw them.
• Use standard exceptions as far as possible.
• Document all checked exceptions thrown by each method using the
@throws tag or @exception tag in the method’s java doc.
13. Recommendation – part 2
• Include appropriate details from the surrounding
context when creating & throwing exceptions.
• Log or print the root exception before you throw a new
wrapped exception.
• Avoid empty catch blocks – swallowing exceptions –
hides errors and exceptions – leaves object or
application in a corrupt or unusable state.
• Exceptions are costly in terms of performance =>
minimize use of checked exceptions, try to convert
checked exceptions into unchecked exceptions.
Notas do Editor
Exception hierarchy can also exist for user defined application exceptions.