User Defined Exception in Java with Real-time example

User Defined Exception in Java with a real-life example and code. You’ll learn how to use this exception in a class.

User defined exception means you write your own custom exception class to use in a program. If an exception occurs, it throws the exception. You can use your custom message to show to the users for their quick issue understanding as well.

For example – you’ve written a program in which you find a city by zip code. If the city is not found, you can throw an exception with a message that “City not found”.

Here’s How to Write User Defined Exception class?

Create a class and extend it with the already available Exception class. In the constructor, receive a message that will be shown to users when exception occurs. Pass this message to the base class Exception’s constructor using super keyword as shown below.

class CityNotFoundException extends Exception {

	public CityNotFoundException(String messageForUser) {

		super(messageForUser);
	}
}

NOTE: if the super is not used then only exception will be thrown and message will not be printed.

Here’s how to use the User Defined Exception in a class

Let’s create a City class that contains the list of the city with its zip code. We’ll maintain zip code as a key and city name as a value in a hash map data structure.

It contains findCityByZipCode(int zipCode) method. If it doesn’t find city name, then it’ll throw the exception “City not found”.

class City {
	Map<Integer, String> list;

	City() {
		list = new HashMap<Integer, String>();
		list.put(400019, "Mumbai");
		list.put(700002, "Kolkata");
		list.put(100025, "Delhi");
		list.put(500004, "Hyderabad");

	}

	// find city by zip code. If no city found throw
	// a user defined exception
	public String findCityByZipCode(int zipCode) throws CityNotFoundException {

		if (list.containsKey(zipCode)) {

			String value = list.get(zipCode);

			return value;
		} else {
			throw new CityNotFoundException("City not found");

		}

	}
}

Test User Defined exception

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Sample {

	public static void main(String[] args) throws CityNotFoundException {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter zip code:");
		int zipCode = sc.nextInt();

		// Find city by Zip code
		City c = new City();
		String city = c.findCityByZipCode(zipCode);
		System.out.println(city);
	}
}

OUTPUT:

Enter zip code:
123456
Exception in thread “main” CityNotFoundException: City not found

Related Posts