Java Custom Exception


We’ll show how user-defined exceptions are implemented and used for both checked and unchecked exceptions.

The Need for Custom Exceptions

Java exceptions cover almost all general exceptions that are bound to happen in programming.
However, we sometimes need to supplement these standard exceptions with our own.
The main reasons for introducing custom exceptions are:

  1. Business logic exceptions – Exceptions that are specific to the business logic and workflow. These help the application users or the developers understand what the exact problem is

  2. To catch and provide specific treatment to a subset of existing Java exceptions

Java exceptions can be checked and unchecked. In the next sections, we’ll cover both of these cases.

Custom Checked Exception

Checked exceptions are exceptions that need to be treated explicitly.

Let’s consider a piece of code which returns the first line of the file:

try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) return file.nextLine(); } catch(FileNotFoundException e) { // Logging, etc }

The code above is a classic way of handling Java checked exceptions. While the code throws FileNotFoundException, it’s not clear what the exact cause is – whether the file doesn’t exist or the file name is invalid.

To create a custom exception, we have to extend the java.lang.Exception class.

Let’s see an example of this by creating custom checked exception called IncorrectFileNameException:

public class IncorrectFileNameException extends Exception { public IncorrectFileNameException(String errorMessage) { super(errorMessage); } }

Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.

This is all we need to do to define a custom exception.

Next, let’s see how we can use the custom exception in our example:

try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) return file.nextLine(); } catch (FileNotFoundException e) { if (!isCorrectFileName(fileName)) { throw new IncorrectFileNameException("Incorrect filename : " + fileName ); } //... }

We’ve created and used a custom exception, so the user can now know what the exact exception is. Is this enough? We are consequently losing the root cause of the exception.

To fix this, we can also add a java.lang.Throwable parameter to the constructor. This way, we can pass the root exception to the method call:

public IncorrectFileNameException(String errorMessage, Throwable err) { super(errorMessage, err); }
Now, the IncorrectFileNameException is used along with the root cause of the exception like this:
try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) { return file.nextLine(); } } catch (FileNotFoundException err) { if (!isCorrectFileName(fileName)) { throw new IncorrectFileNameException( "Incorrect filename : " + fileName , err); } // ... }

This is how we can use custom exceptions without losing the root cause from which they occurred.

Custom Unchecked Exception

In our same example, let’s assume that we need a custom exception if the file name doesn’t contain any extension.

In this case, we’ll need a custom unchecked exception similar to the previous one, as this error will only be detected during runtime.

To create a custom unchecked exception we need to extend the java.lang.RuntimeException class:
public class IncorrectFileExtensionException extends RuntimeException { public IncorrectFileExtensionException(String errorMessage, Throwable err) { super(errorMessage, err); } }
Hence, we can use this custom unchecked exception in our example:
try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) { return file.nextLine(); } else { throw new IllegalArgumentException("Non readable file"); } } catch (FileNotFoundException err) { if (!isCorrectFileName(fileName)) { throw new IncorrectFileNameException( "Incorrect filename : " + fileName , err); } //... } catch(IllegalArgumentException err) { if(!containsExtension(fileName)) { throw new IncorrectFileExtensionException( "Filename does not contain extension : " + fileName, err); } //... }
simple example of java custom exception.
class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } }

class Test { static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } }

Exception occured: InvalidAgeException:not valid rest of the code...

Custom exceptions are very much useful when we need to handle specific exceptions related to the business logic. When used properly, they can serve as a useful tool for better exception handling and logging.