Romer Alvarez
← All posts

Exception handling in Java: an introduction.

Exceptions

When we write programs, it’s normal for them to have errors. Sometimes unexpected things happen while the program is running, and they can interrupt its normal flow. That is what we call an exception.

In Java, exceptions are how we handle these errors. Exceptions are special objects that make error handling simple and decoupled.

Exceptions give us several advantages:

try/catch/finally syntax

try {
  [block that throws the exception]
} catch(Exception e) {
  [block where the error is handled]
} finally {
  [optional block that always runs]
}

The Exception class

Throwing an exception means throwing an instance of the Exception class or of one of its subclasses. The Exception class has two constructors and two important methods.

// Empty constructor
Exception e = new Exception();

// Constructor with a message
String mensaje = "Mensaje de error";
Exception e = new Exception(mensaje);
// Summary of the message
String mensaje = e.getMessage();

// The whole stack where the error started
e.printStackTrace();

In the next post we go deeper into the kinds of exceptions there are: checked and unchecked exceptions.