- How to create a user defined exception (custom exception) in java?
- Example
- Output
- User defined exceptions
- Example
- Output
- User defined exception in java
- Example of User defined exception in Java
- Another Example of Custom Exception
- Top Related Articles:
- About the Author
- Comments
- Create user defined exceptions in java
- How to Create a User-Defined Exception in Java
- How to Create a User-Defined Exception in Java?
- Method 1: Create a User-Defined Exception in Java Using getMessage() Method
- Example 1
- Example 2
- Method 2: Create a User-Defined Exception Using toString() Method
- Example
- Conclusion
- About the author
- Farah Batool
How to create a user defined exception (custom exception) in java?
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Example
import java.util.Scanner; public class ExceptionExample < public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: "+c); >>
Output
Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)
User defined exceptions
You can create your own exceptions in Java.
- All exceptions must be a child of Throwable.
- If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
- If you want to write a runtime exception, you need to extend the RuntimeException class.
To create a user defined exception extend one of the above mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor by passing the message in String format.
AgeDoesnotMatchException(String msg) < super(msg); >Or, public String toString()
Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.
MyException ex = new MyException (); If(condition……….)
Example
In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException.
public class AgeDoesnotMatchException extends Exception < (String msg)< super(msg); >>
Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables.
Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values.
In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24.
public class Student extends RuntimeException < private String name; private int age; public Student(String name, int age)< try < if (age<17||age>24) < String msg = "Age is not between 17 and 24"; AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg); throw ex; >> catch(AgeDoesnotMatchException e) < e.printStackTrace(); >this.name = name; this.age = age; > public void display() < System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); >public static void main(String args[]) < Scanner sc= new Scanner(System.in); System.out.println("Enter the name of the Student: "); String name = sc.next(); System.out.println("Enter the age of the Student should be 17 to 24 (including 17 and 24): "); int age = sc.nextInt(); Student obj = new Student(name, age); obj.display(); >>
Output
On executing this program, you need to pass name and age values from keyboard. If the given age value id not between 17 and 24 then exception occurs as shown below −
Enter the name of the Student: Krishna Enter the age of the Student should be 17 to 24 (including 17 and 24): 14 AgeDoesnotMatchException: Age is not between 17 and 24 Name of the Student: Krishna' Age of the Student: 14 at Student.(Student.java:18) at Student.main(Student.java:39)
User defined exception in java
In java we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException, In the last tutorial we learnt how to throw these exceptions explicitly based on your conditions using throw keyword.
In java we can create our own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions. In this tutorial we will see how to create your own custom exception and throw it on a particular condition.
To understand this tutorial you should have the basic knowledge of try-catch block and throw in java.
Example of User defined exception in Java
/* This is my Exception class, I have named it MyException * you can give any name, just remember that it should * extend Exception class */ class MyException extends Exception < String str1; /* Constructor of custom exception class * here I am copying the message that we are passing while * throwing the exception to a string and then displaying * that string along with the message. */ MyException(String str2) < str1=str2; >public String toString() < return ("MyException Occurred: "+str1) ; >> class Example1 < public static void main(String args[])< try< System.out.println("Starting of try block"); // I'm throwing the custom exception using throw throw new MyException("This is My error Message"); >catch(MyException exp) < System.out.println("Catch Block") ; System.out.println(exp) ; >> >
Starting of try block Catch Block MyException Occurred: This is My error Message
Explanation:
You can see that while throwing custom exception I gave a string in parenthesis ( throw new MyException(«This is My error Message»); ). That’s why we have a parameterized constructor (with a String parameter) in my custom exception class.
Notes:
1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.
Another Example of Custom Exception
In this example we are throwing an exception from a method. In this case we should use throws clause in the method signature otherwise you will get compilation error saying that “unhandled exception in method”. To understand how throws clause works, refer this guide: throws keyword in java.
class InvalidProductException extends Exception < public InvalidProductException(String s) < // Call constructor of parent Exception super(s); >> public class Example1 < void productCheck(int weight) throws InvalidProductException< if(weight<100)< throw new InvalidProductException("Product Invalid"); >> public static void main(String args[]) < Example1 obj = new Example1(); try < obj.productCheck(60); >catch (InvalidProductException ex) < System.out.println("Caught the exception"); System.out.println(ex.getMessage()); >> >
Caught the exception Product Invalid
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
Hi Sir,
In the first example
public String toString() return (“Output String = “+str1) ;
>
when this block of code is called. I used breakpoint to check when this block is executed. but couldnt really understand what is happening. Please explain this.
Gopinath actually when
System.out.println(exp) ; is executed as we are passing Object type to println() toString() method is called, here they have overrided the toString() so we get the output: Output String = Custom Hope this helps
ya we can do it. if you want to write user define exception you need to catch that exception and your class should extends from RuntimeException and you need to write cause for exception
Create user defined exceptions in java
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
How to Create a User-Defined Exception in Java
A run-time error that happens while a process is executed is an exception. The program abruptly ends when an exception occurs, and the code after the line that caused the exception will not execute. In Java, exception classes such as ArithmeticException, and NullPointerException are already defined in the “Exception” class. However, you can make a user-defined exception in Java and use the throw keyword with them.
This manual will teach the method of creating Java user-defined exceptions.
How to Create a User-Defined Exception in Java?
In Java, you can create an exception and throw it utilizing the “throw” keyword. User-defined or custom exceptions are the names given to these exceptions.
To create a user-defined exception, first, you will extend the class with the “Exception” class and then use one of the below-mentioned methods:
Let’s understand both methods for creating user-defined exceptions with examples.
Method 1: Create a User-Defined Exception in Java Using getMessage() Method
In this section, we will use a “getMessage()” method to throw an exception with the “throw” keyword. We will pass a String that is used as an exception to the constructor of the parent “Exception” class by invoking the “super()” method in the present class constructor.
Follow the given syntax for user-defined exception:
Example 1
First, we will extend our class to the “Exception” class, then create a parameterized constructor that takes a String which will be thrown as an exception. In the constructor of the “Example” class, we will pass the String type parameter “s” and call the “super()” method with argument “s” that is passed to a constructor of the parent class:
In the main() method, first we will create an object of the class and pass a string as an argument because the class contains a parameterized constructor. Then, throw an exception with the object of the class. These operations will be added in a try-catch block. Next, in the catch block, we will call the getMessage() method to print the message passed to the parent Exception class using the super() method:
publicstaticvoidmain ( String [ ] args ) {
try {
Example ex = new Example ( «Invalid Entry» ) ;
throw ex ;
} catch ( Example e ) {
System . out . println ( «Caught exception» ) ;
System . out . println ( e. getMessage ( ) ) ;
}
}
The user-defined exception is thrown:
It is not mandatory that you pass a String to a parent class using the super() method, you can also create a user-defined exception by calling a parent’s constructor without passing any parameter.
Example 2
In this example, we will create a user-defined exception without printing any message. Here, first, we will create a “UserDefinedException” class that extends to the “Exception” class:
In the main() method of the “Example” class, we will throw an exception by creating a new object of the user-defined exception class. In the catch block, we will call the getMessage() method to print the message; however, it will print none because we will not pass any message to it:
publicclassExample {
publicstaticvoidmain ( String [ ] args ) {
try {
thrownew UserDefinedException ( ) ;
} catch ( UserDefinedException ue ) {
System . out . println ( «Caught exception» ) ;
System . out . println ( ue. getMessage ( ) ) ;
}
}
}
Let’s see how we can print exception details rather than specifying it in the parent class constructor.
Method 2: Create a User-Defined Exception Using toString() Method
If you want to print some details related to the exception, use the “toString()” method.
Use the given syntax for printing message in user-defined exception:
Example
Here, we will create a toString() method in the user-defined exception class called “UserDefinedException“ by extending it with an “Exception” class. The method will return the string that will be printed out:
classUserDefinedExceptionextendsException {
public String toString ( ) {
return ( «The Exception is occured» ) ;
}
}
In the main() method, we will call throw the exception using the “throw” keyword by creating a new object of the user-defined class in a try block:
publicclassExample {
publicstaticvoidmain ( String [ ] args ) {
try {
thrownew UserDefinedException ( ) ;
} catch ( UserDefinedException ue ) {
System . out . println ( «Caught exception» ) ;
System . out . println ( ue ) ;
}
}
}
We have compiled all the ways to create a user-defined exception in Java.
Conclusion
For creating a user-defined exception in Java, you will first extend the class to the Exception class, then use two methods, getMessage() and toString() methods. These methods are used to print the messages as an exception. The getMessage() method prints the message passed to the parent class constructor, while the toString() method returns the string that will be used as an exception message. In this manual, we explained the methods for creating a Java user-defined exception with examples.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.