Java Custom Exception Sample Code

Why is it a good idea to create your own Java custom exception? Good question. A custom exception allows you to handle each specific problem separately as opposed to something bad just happened.

Coding your Java Exception is pretty simple. Create your custom exception by extending the exception class and calling super() as the first line of the custom exception constructor. To illustrate this, I provided four code snippets below. The sample output at the bottom after running shows the new custom exception along with the included message.


Create Custom Exception:

class WorkerNotFoundException extends Exception
{
	public WorkerNotFoundException(String message)
	{
		super(message);
	}
}


Create Class to Throw Custom Exception:

class MyWorker
{
	 public Worker processID(int workerID) throws WorkerNotFoundException
	 {
	        if (workerID == 12345) 
	        {
	            return new Worker();
	        } 
	        else 
	        {
	            throw new WorkerNotFoundException("Could not find workerID: " + workerID);
	        }
	 }
}


Create Class to Catch Custom Exception:

package com.jcd.java.tutorials;

public class JavaCustomException {

	public static void main(String[] args) 
	{
		MyWorker myWorker = new MyWorker();
		 
        try {
 
            Worker worker = myWorker.processID(123456);
 
        } 
        catch (WorkerNotFoundException ex) 
        {
            System.out.println(ex.toString());
        }

	}

}


Create Worker Class:

class Worker 
{
	public Worker()
	{
		
	}
}


Java Custom Exception Output:

com.jcd.java.tutorials.WorkerNotFoundException: Could not find workerID: 123456



References:

Add a Comment

Your email address will not be published. Required fields are marked *