Exceptions
Last updated
Last updated
An exception occurs when something unintended occurs and the interpreter must exit.
While this might sound like a bad thing, we can often throw our own exceptions to handle known errors or edge cases more gracefully.
In Java, there are two types of exceptions: checked and unchecked.
Checked exceptions are handled during compile time, and are included in the method declaration. As an example:
All children that override this method must also throw the same exceptions.
Unchecked exceptions are not handled during compile time, and thus are thrown during runtime. All Error
or RuntimeException
types are unchecked; all other exceptions are checked. Some examples of unchecked exceptions are dividing by zero (ArithmeticException
), or accessing an index that doesn't exist (IndexOutOfBoundsException
).
We can use the throw
keyword to create exceptions with custom error messages as follows:
This is often used within a try catch
block, as such:
An alternate to custom exceptions is to simply handle exception cases. For example, we can add a check to make sure a number is not zero before running a division operation.
Let's check your understanding of exception handling!
What will be printed (and in what order) when tryCatchFinally()
is run?
Suppose the same code were run, but without the catch
block. What would this code do?