Home > Tutorial > Java Custom Exception Sample Code

Java Custom Exception Sample Code

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:

Smedley
Posted by

Smedley

Smedley has been doing software development for years, which mainly docues on C and C++. In the past number of years, he has focused on Java programming.

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot