Coders Packet

User Defined Exception in Java with an example

By Adinath Kishor Joshi

Hello Learners, in this article, we will learn about how to create a User-defined exception and exception handling in Java

When an error occurs within a method, the method creates an exception object which contains information about the error. This object is then handed to the system. This is called throwing an exception. The exceptions are catched by the method using the combination of the try and catch keywords that are used in the code and are used to generate exceptions. In this case, as an example, Odd number exception is shown.

Let us look at the algorithm and code:


Firstly, import the necessary packages.

Create a class that represents the user-defined exception.

Call the constructor of the parent exception and type the exception message.

import java.util.Scanner;
class OddNumberException extends Exception {
OddNumberException() {
super("Invalid input:Odd number ");
OddNumberException(String msg) {

Create a class that uses the above class OddNumberException and take necessary inputs.

public class UserdefinedException
    { public static void main(String[] args){
            int num;
            Scanner Sc = new Scanner(;
            System.out.println("Enter only even number : ");
            num = Integer.parseInt(Sc.nextLine());

The throw is used to create a new exception and throw it. If the input number is an odd number throw the object of OddNumberException.

If an input number is an even number print the necessary statements and the program is ended successfully.

try {
if (num % 2 != 0) throw (new OddNumberException());
else System.out.println(num + " is an even number");
catch(OddNumberException e) {
System.out.println("Error :" + e.getMessage());
System.out.println("End of program");


Save, Compile & Run the code. The expected output is:

C:\java>java UserdefinedException
Enter only even number :
Error :Invalid input:Odd number
End of program


Download Complete Code


No comments yet