# Exceptions

Source: https://wisconsin.twango.dev/fa24-cs300/u1-java-programming/exceptions

# Exceptions

Exceptions are a way to handle errors in Java. They are objects that are thrown when an error occurs in a program. When an exception is thrown, the program stops executing and the exception is passed to the calling method. If the calling method does not handle the exception, the exception is passed to the next method in the call stack. If no method handles the exception, the program terminates.

Generally, you should use exceptions to handle errors that are outside your control.

An exception essentially just throws the responsibility of handling the error to the calling method. This allows you to separate the error handling code from the normal code, making your code cleaner and easier to read.

## Throwing Exceptions
To throw an exception in Java, you use the `throw` keyword followed by an instance of an exception class. For example, to throw an `ArithmeticException`, you would write:

```java
throw new ArithmeticException("Division by zero");
```

## Handling Exceptions

There are two ways to handle exceptions in Java: using a `try-catch` block or using a `throws` clause.

### Try-Catch Blocks
A `try-catch` block is used to catch exceptions that are thrown in the `try` block. If an exception is thrown in the `try` block, the program will jump to the `catch` block and execute the code there. If no exception is thrown, the `catch` block is skipped.

```java
try {
    // code that may throw an exception
} catch (Exception e) {
    // code to handle the exception
}
```

### Throws Clause
A `throws` clause is used to declare that a method may throw an exception. If a method throws an exception and does not handle it, the exception is passed to the calling method. If the calling method does not handle the exception, the exception is passed to the next method in the call stack.

```java
public void myMethod() throws Exception {
    // code that may throw an exception
}
```

> [!question]- Question: Throw vs. Throws
> What is the difference between `throw` and `throws` in Java?
>
> - `throw` is used to throw an exception in a method.
> - `throws` is used to declare that a method may throw an exception.

## Exception Hierarchy

In Java, exceptions are organized in a hierarchy. At the top of the hierarchy is the `Throwable` class, which is the superclass of all exceptions and errors in Java. The `Throwable` class has two subclasses: `Exception` and `Error`.

- `Exception` is the superclass of all checked exceptions in Java. Checked exceptions are exceptions that must be caught or declared in the method signature.
- `RuntimeException` is the superclass of all unchecked exceptions in Java, a subclass of `Exception`. Unchecked exceptions are exceptions that do not need to be caught or declared in the method signature.

When catching exceptions, the order of the catch blocks is important. You should catch the most specific exceptions first and the most general exceptions last, as catch blocks traverse the exception hierarchy from top to bottom.

> [!example]
> The following is an example of catching exceptions in Java:
>
> ```java
> try {
>     // code that may throw an exception
> } catch (ArithmeticException e) {
>     // code to handle the ArithmeticException
> } catch (Exception e) {
>     // code to handle any other exceptions
> }
> ```


### Checked vs. Unchecked Exceptions

Checked exceptions are exceptions that must be caught or declared in the method signature. They are subclasses of `Exception` (but not `RuntimeException`).

Unchecked exceptions are exceptions that do not need to be caught or declared in the method signature. They include subclasses of `RuntimeException` and `Error`.

> [!example]
> The following is an example of a checked exception:
>
> ```java
> public void readFile() throws IOException {
>     // code that may throw an IOException
> }
> ```

The following is an example of an unchecked exception:

```java
public void divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Division by zero");
    }
}
```

## Source

The existing course note was retained and normalized during the merge.

Related: [[u1-java-programming/index|Topic index]].
