Handling Exceptions

Discover how to handle and throw custom exceptions effectively and precise error-handling techniques.

Introduction to exceptions

An exception is a generally unwanted event that interrupts the regular flow of our program. It might occur when we perform an illegal operation. Exceptions contain information that helps developers find out what led to this problem.

Example 1: Division by zero

Let’s take a look at an example. When we divide an integer by 0, an exception of type ArithmeticException will be thrown.

  • Each exception might have a message included that should explain what went wrong. In this case, the message will be / by zero.

  • Each exception also includes its stack trace, which is a list of the method calls that the application was in the middle of when the exception was thrown.

In this example, it includes information that this exception was thrown from the calculate function, which was called from the printCalculated function, which was called from the main function.

Remember: An exception interrupts program execution, so statements after it won’t be executed. In the example below, notice that After is never printed.

Get hands-on with 1400+ tech skills courses.