Skip to main content

How to Catch a Specific Exception in Java

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When something goes wrong in Java, the code throws an exception, and the program stops unless a catch handles it. A catch that names one exception type handles the failure you expected and lets every other one through, so real bugs still show up.

Syntax​

Syntax
try {
<code that may throw>
} catch (<ExceptionType> <e>) {
<handle it, for example with <e>.getMessage()>
}
PartWhat it does
try { ... }Runs the code that may throw.
catch (<ExceptionType> <e>)Runs only for that type, or a subclass of it.
<e>.getMessage()The exception's description.

The Java Language Specification, section 14.20: "If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause."

The Example​

The example turns text into a number with Integer.parseInt. For forty-two that throws a NumberFormatException; the catch prints the reason and returns 0.

Prerequisites​

  • A JDK, the Java Development Kit. java Main.java runs a single file without compiling it first. This guide uses OpenJDK 25.0.5.1.

Step 1: Write the Code​

Create a file named Main.java:

Main.java, which defines toNumber(String text) that returns Integer.parseInt(text) inside try, catches NumberFormatException e, prints Not a number: with e.getMessage() and returns 0, and prints toNumber("42") and toNumber("forty-two").

Main.java
public class Main {
static int toNumber(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
return 0;
}
}

public static void main(String[] args) {
System.out.println(toNumber("42"));
System.out.println(toNumber("forty-two"));
}
}

Step 2: Run It​

Terminal
java Main.java
Output
42
Not a number: For input string: "forty-two"
0

A zsh terminal where java Main.java prints 42, Not a number: For input string: "forty-two", and 0.

The first call never reached the catch. The second threw, the catch printed the message, and the program carried on. The command is the same in zsh, bash and PowerShell.

Catching a Superclass​

Exceptions form a family tree: NumberFormatException extends IllegalArgumentException, which extends RuntimeException. A catch (IllegalArgumentException e) therefore catches a NumberFormatException too, along with its other subclasses. Catch the specific type when only that failure is expected, and a superclass when a whole family should be handled the same way.

When you catch both, list the subclass first; the compiler refuses a catch that can never run.

Common Mistakes​

MistakeWhat happensDo this instead
Catching the superclass above the subclasserror: exception NumberFormatException has already been caughtPut the specific type first
Catching Exception around a lot of codeReal bugs are handled as if they were the expected failureCatch the specific type, around as little code as possible
An empty catch blockThe failure disappears silentlyAt least print or log e.getMessage()

Troubleshooting​

SymptomLikely causeFix
The program still stops with Exception in thread "main"The exception isn't the type you catchRead the type on that line and catch it
has already been caughtA broader catch sits aboveReorder the clauses

FAQ​

Can one catch handle several types?​

Yes, with |: catch (NumberFormatException | NullPointerException e).

Do I have to catch every exception?​

Only checked exceptions, such as IOException, must be caught or declared. NumberFormatException is unchecked, so catching it is your choice.

Conclusion​

catch (SomeException e) handles one kind of failure and gives you e.getMessage(); everything else keeps going up. List subclasses before superclasses.

Additional Resources​