What is the correct way to create a Java custom exception? I want to define my own exception type and throw it when a specific condition is met.
For example, in a try
block, I read a string using reader.readLine()
, and if the string contains a space, I need to throw my custom exception.
However, when I use throw new...
, I get an error saying “unreported exception… must be caught or declared to be thrown”.
How should I properly create and handle a custom exception in Java?
So, creating a java custom exception starts by extending the Exception
class. This approach will create a checked exception, meaning Java requires you to either catch it or declare it in the method signature with throws
. This is helpful if you want to enforce that the exception is handled by whoever is calling your method.
Here’s a quick example:
Step 1: Create Your Custom Exception Class
class SpaceNotAllowedException extends Exception {
public SpaceNotAllowedException(String message) {
super(message);
}
}
Step 2: Throw It When Needed
try {
String word = reader.readLine();
if (word.contains(" ")) {
throw new SpaceNotAllowedException("Spaces are not allowed in input.");
}
} catch (SpaceNotAllowedException e) {
System.out.println("Error: " + e.getMessage());
}
Why this works: Since SpaceNotAllowedException
extends Exception
, Java requires it to be caught or declared using throws
. This makes sure the exception is properly dealt with, keeping your code robust.
Totally! But what if you don’t want the calling code to be forced into handling the exception? That’s where an unchecked exception can come in handy. Instead of extending Exception
, you can extend RuntimeException
. This way, your custom exception becomes an unchecked exception, and Java won’t require you to catch it or declare it with throws
.
Custom Unchecked Exception
class SpaceNotAllowedException extends RuntimeException {
public SpaceNotAllowedException(String message) {
super(message);
}
}
Throw It Without Try-Catch
String word = reader.readLine();
if (word.contains(" ")) {
throw new SpaceNotAllowedException("Spaces are not allowed!");
}
Why this works: With unchecked exceptions, you’re not forced to handle them right away, keeping your code a little cleaner and easier to work with. You can always handle it later if needed, but it won’t block your method flow.
And you can also mix it up a bit by declaring the java custom exception in your method’s signature using throws
. This allows the exception to bubble up the call stack, letting the caller decide how to handle it. It’s a bit more flexible and can be useful in more complex scenarios where you don’t want to immediately deal with the exception in the current method.
Modify Your Method
void checkWord() throws SpaceNotAllowedException, IOException {
String word = reader.readLine();
if (word.contains(" ")) {
throw new SpaceNotAllowedException("Input contains spaces!");
}
}
Call It and Handle the Exception
try {
checkWord();
} catch (SpaceNotAllowedException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
Why this works: The throws
keyword in the method signature tells the compiler that this method might throw a java custom exception. This way, whoever is calling checkWord()
has to handle it, making the code more predictable and manageable.