📕
Knowledge
  • Knowledge Repository
  • Java
    • Intro
    • Persistence
      • Java Persistence API (JPA)
        • Entity Manager
        • Transaction Management
        • Relationship Mapping
      • Java Transaction API (JTA)
    • Resources
  • Angular
    • Intro
    • Overview
    • CLI Commands
    • Directives
  • Tools
    • IDEs
      • IntelliJ
        • Shortcuts
  • Book Notes
    • Intro
    • Java A Beginner's Guide
      • Chapter 1. Java Fundamentals
      • Chapter 2. Data Types and Operators
      • Chapter 3. Program Control Statements
      • Chapter 4. Introducing Classes, Objects, and Methods
      • Chapter 5. More Data Types & Operators
      • Chapter 6. Closer Look At Methods and Classes
      • Chapter 7. Inheritance
      • Chapter 8. Packages & Interfaces
      • Chapter 9. Exception Handling
      • Chapter 10. Using I/O
    • Data Pipelines With Airflow
      • Chapter 1. Meet Airflow
      • Chapter 2. Anatomy Of a DAG
  • Course Notes
    • Intro
    • Spring: TDD With JUnit
Powered by GitBook
On this page
  • Exception Hierarchy
  • Handling Fundamentals
  • Try Catch Block
  • Consequences of Uncaught Exceptions
  • Throwing an Exception
  • Rethrowing an Exception
  • Throwable Methods
  • Using Finally

Was this helpful?

  1. Book Notes
  2. Java A Beginner's Guide

Chapter 9. Exception Handling

An exception is an error that happens at run time of your application, and utilising Java's exception handling subsystem you can handle these run-time errors in a controlled manner.

Exceptions in Java streamline error handling by allowing your program to define a block of code called exception handler that executes when an error occurs.

Exception Hierarchy

All exceptions in Java are represented as classes and they are all derived from a class called Throwable. Throwable has two direct subclasses, Exception and *Error. Error type are related to issue with the JVM itself and not your program.

Any errors can occur in your program are represented by subclasses of Exception.

One key important subclass of Exception is RuntimeException, which is used to represent various common types of run-time errors.

Handling Fundamentals

An exception handling block uses five keywords:

  • try

  • catch

  • throw

  • throws

  • finally

These keywords form an interrelated system in which the use of one of them connects to another.

Blocks of code that you want to monitor for exceptions are contained in the try block. If an exception occurs, it is thrown and your code can catch this with the catch and handle it in the catch block. If you need to re-throw a new exception, you can manually do this with throw. In cases where an exception is thrown out of a method, this must be specified using the throws clause in the method. Finally is used to execute any code that must happen upon existing from the try block.

Try Catch Block

try {
  //  Block of code to try
}
catch (Exception e) {
  //  Block of code to handle errors
}

The above scenario is using the parent Exception class and so any exception type will be caught. If you need to specify granular exceptions then you can add multiple catch blocks each specifying a particular exception type so they can be handled in different ways.

It is the job of your exception handler to remedy the problem that caused the exception so that the program can continue normally.

Consequences of Uncaught Exceptions

Catching an exception and dealing with it prevents abnormal program termination. However, if you don't catch an exception when it occurs then it will be caught by the JVM. This can be an issue because the default handler in the JVM terminates execution and displays a stack trace. This is useful for debugging purposes but not something that you would want any users to see.

Throwing an Exception

Alongside catching automatically thrown exceptions from the JVM, you can choose to throw your own Exceptions in certain situations.

throw new Exception("Exception message");

Exceptions are objects, which is why they must be 'newed' up. Not all exceptions require a message passing into the body.

Rethrowing an Exception

An exception caught by one catch statement can be rethrown to be caught by an outer catch. This is typically used when your exception handlers (catch blocks) handle the exception in different ways. The first may perform one particular action and the second another. When you rethrow an exception it propagates up to the next catch and will never be caught by the same handler.

Throwable Methods

All exceptions are subclasses of throwable and so inherit methods definded by it. Some of the most commonly used ones are:

Method
Description

Throwable fillInStackTrace()

Returns a Throwable object that contains a completed stack trace. Can be rethrown.

String getLocalizedMessage()

Returns a localized description of the exception.

String getMessage()

Returns a description of the exception.

void printStackTrace()

Displays the stack trace.

void printStackTrace(PrintStream stream)

Sends the stack trace to the specified stream.

void printStackTrace(PrintWriter stream)

Sends the stack trace to the specified stream.

String toString()

Returns a String object containing a complete description of the exception.

Using Finally

Sometimes when you require a final operation to happen even after a catch block has executed and throw an exception, you can use the finally block which will execute as the last step in the try/catch/finally block. Typically, used to close a file or network connection.

PreviousChapter 8. Packages & InterfacesNextChapter 10. Using I/O

Last updated 3 years ago

Was this helpful?