Drills in Java Exceptions

Revise Java’s Exception Handling Mechanism Quickly

George Marklow

--

Photo by Steve Johnson on Unsplash

Introduction

This article can help you if you’re already familiar with Java exception handling and you need to:

  1. Prepare for interviews, or
  2. Reacquaint yourself with the language after a period away from Java exception handling e.g. moving from frontend to a backend project.

Each part consists of a “drill” that explores topics in Java exception handling.

Names of variables and methods are kept deliberately short to minimize the amount of typing required to complete the code exercises.

What This Article Is Not

This article is about learning by doing and doesn’t offer thorough explanations of the topics explored in the code drills. You’re left to explore these operations in more detail in your own time.

Setup

You can work with Java immediately using an online IDE such as Repl.

On the top left-hand side, click the Create button and search for Java in the Template dropdown list as shown below, then click Create Repl.

(You can also follow these instructions to install the latest version of Java on your computer, and download an IDE such as Eclipse or Netbeans).

Click the Run button — the console should print “Hello World”:

To make it quicker (and easier to read), print to the console using this method:

static void o(Object x) {
System.out.println(x);
}

To test this out, change the main method as follows to print the sum of two numbers:

public static void main(String[] args) {
o(2 + 2);
}

Next, copy and paste the following imports above the Main class:

import java.lang.Math;
import java.util.*;

Now, add the following overloaded method to print arrays nicely:

static void o(String[] x) {
o(Arrays.toString(x));
}

Your code should look like this:

import java.lang.Math;
import java.util.*;
class Main {
public static void main(String[] args) {
o(2 + 2);
}

static void o(Object x) {
System.out.println(x);
}
static void o(String[] x) {
o(Arrays.toString(x));
}
}

We’re now ready to begin the drills!

Please note the following:

  • The result of code execution is placed on the right after //.
  • Code that throws an exception is marked with 🔥.
  • Code that doesn’t compile is marked with ❌.

Try-Catch-Finally

int d = 0;
int a = 1/d; // 🔥
try {
int d = 0;
int a = 1/d;
o("a");
} catch (ArithmeticException e) {
o("b");
} finally {
o("c");
} // "b"
// "c"
try {
int x[] = { 1 };
x[1] = 2;
o("a");
} catch (ArithmeticException e) {
o("b");
} catch (ArrayIndexOutOfBoundsException e) {
o("c");
} finally {
o("d");
} // "c"
// "d"
try {
} catch (Exception e) {
} catch (ArrayIndexOutOfBoundsException e) {
} finally {
} // ❌

Throwing Exceptions

Create the following method:

static void x() {
try {
throw new ArithmeticException("a");
} catch (ArithmeticException e) {
o(e.getMessage());
throw e;
}
}

And continue the drill inside main:

try {
x();
} catch (ArithmeticException e) {
o(String.format("recaught %s", e.getMessage()));
} // "a"
// "recaught a"

Now remove the exception handling in main and call method x:

public static void main(String[] args) {
x();
} // ❌

Update main method declaration, including a throws clause, so that program compiles normally:

public static void main(String[] args) 
throws ArithmeticException {
x();
} // "a"
// "recaught a"

Custom Exceptions

Create a new class for a custom exception E that specifies an exception message:

class E extends Exception {
private int n;

E(int x) {
n = x;
}
public String toString() {
return String.format("E[%s]", n);
}
}

In the Main class, add a method f(x) that throws this custom exception for negative integers when called from the main method:

class Main {    static void f(int x) throws E {
o(String.format("f(%s)", x));

if (x < 0) {
throw new E(x);
}

o("ok");
}
public static void main(String[] args) {
try {
f(1);
f(-1);
} catch (E e) {
o(String.format("Caught %s", e));
}
}
}

This prints:

"f(1)"
"ok"
"f(-1)"
"caught E[-1]"

Multi-Catch

Create the following empty custom exception classes:

class P extends Exception { }
class Q extends Exception { }

Update the main method in the Main class as follows:

try {
if (new Random().nextInt(2) == 1) {
throw new P();
}
throw new Q();
} catch (P | Q ex) {
o(ex);
}

The random number generator will draw a number 0 or 1 with a 50% probability, throwing either P or Q exceptions that are caught and printed in the catch block:

"P"
"Q"
"Q"
"P"
"P"

Thanks for reading! Let me know what you think in the comments section below, and don’t forget to subscribe. 👍

--

--

George Marklow

George is a software engineer, author, blogger, and abstract artist who believes in helping others to make us happier and healthier.