Exceptions in Java

Exceptions in Java

Exception Throwing

  • Exceptions can only be thrown by methods, not by types or declarations.
  • Constructors can throw exceptions as they are considered a type of method.
  • Exceptions are thrown by methods, not individual lines of code.

Exception Hierarchy

  • All exceptions inherit from the Throwable class.
  • Key exception classes to remember:
    • Exception: Base class for checked exceptions.
    • RuntimeException: Base class for unchecked exceptions.

Checked vs. Unchecked Exceptions

  • Checked Exceptions: Extend from Exception (excluding RuntimeException).
    • Forces the programmer to handle or declare the exception.
    • Good practice for anticipated issues.
  • Unchecked Exceptions: Extend from RuntimeException.
    • Compiler does not force handling or declaration.
    • Suitable for errors that are difficult to recover from.

Valuable Exception Information

  • Exception messages can contain relevant information for debugging.
  • Stack traces provide the call stack leading to the exception.

User-Defined Exceptions

  • Creating custom exception classes allows for specific error handling.
  • Example: NegativeNumberException extending Exception (a checked exception).

Purpose of Custom Exceptions

  • Allows for specific handling of different exception types.
  • Differentiates between expected and unexpected errors.

Throwing Exceptions

  • Exceptions are thrown using the throw keyword followed by a new exception object.
    • Example: throw new NegativeNumberException("Non-negative number, please.");
  • Methods that throw checked exceptions must declare them in their signature using the throws keyword.
    • Example: public int calculateSquareRoot(int input) throws NegativeNumberException

Example Scenario

  • A calculateSquareRoot method throws a NegativeNumberException if the input is negative.

Real-World Considerations

  • User input often requires validation and can lead to exceptions (e.g., NumberFormatException when parsing input).
  • The compiler may force you to include exception types in your method signature if the code within the method call might throw those exceptions.

Handling Exceptions: Try-Catch Blocks

  • Code that might throw an exception is placed within a try block.
  • catch blocks are used to handle specific exception types.
  • Multiple catch blocks can be used to handle different exceptions.
  • Java checks each catch block in order; once a matching catch block is found, it is executed, and the remaining catch blocks are skipped.
  • If you have a hierarchy of exceptions avoid catching the parent first, as that would prevent the child exception catch being called.

Combining Exceptions in Catch Blocks

  • It is possible to catch multiple exceptions in a single catch block.
  • However, it's not possible to catch a specific combination of exceptions (e.g., exception A and exception B only when they both occur).

Exception Types

  • If different conditions warrant different exception types, then different exceptions should be thrown.
  • When an exception is thrown, the code execution within that method stops.
  • Only one exception can be thrown at a time.

Finally Block

  • A finally block is used to execute code that should always run, regardless of whether an exception was thrown.
  • finally blocks are often used for resource cleanup (e.g., closing files).
  • A try block can be followed by catch blocks, a finally block, or both.
  • If an exception occurs within the try block, the remaining code in the try block is skipped, and the appropriate catch block (if any) is executed before the finally block.
  • If no exceptions are thrown the catch block is skipped but the finally block is still executed.

Exception Handling Order

  • catch blocks should be ordered from specific to general exception types.
  • Catching a higher-level exception first can prevent more specific catch blocks from being reached, leading to a compilation error.

Practical Implications

  • Exception handling is crucial when interacting with external resources (e.g., databases, files) where unexpected issues may arise.

Code Example

  • A user-defined exception (MyException) is created, extending the Exception class.
  • The divide method is modified to throw MyException under certain conditions.
  • The main method is updated to handle MyException using a try-catch block.

Notes

  • We can try throwing a new MyUncheckedException inside the try.