- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we create a custom exception in Java?
Sometimes it is required to develop meaningful exceptions based on the application requirements. We can create our own exceptions by extending Exception class in Java
User-defined exceptions in Java are also known as Custom Exceptions.
Steps to create a Custom Exception with an Example
- CustomException class is the custom exception class this class is extending Exception class.
- Create one local variable message to store the exception message locally in the class object.
- We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message.
- toString() method is used to print out the exception message.
- We are simply throwing a CustomException using one try-catch block in the main method and observe how the string is passed while creating a custom exception. Inside the catch block, we are printing out the message.
Example
class CustomException extends Exception { String message; CustomException(String str) { message = str; } public String toString() { return ("Custom Exception Occurred : " + message); } } public class MainException { public static void main(String args[]) { try { throw new CustomException("This is a custom message"); } catch(CustomException e) { System.out.println(e); } } }
Output
Custom Exception Occurred : This is a custom message
- Related Articles
- How to create a user defined exception (custom exception) in java?
- How to create a custom unchecked exception in Java?
- How can we decide that custom exception should be checked or unchecked in java?
- Can we create an enum with custom values in java?
- Is it possible to create a custom exception in java without extending Exception class?
- How can we implement a Custom HashSet in Java?
- How can we implement a custom iterable in Java?
- While chaining, can we throw unchecked exception from a checked exception in java?
- When should we create a user-defined exception class in Java?
- How can we create a login form in Java?
- How can we create a JSON using JsonGenerator in Java?
- How to implement a custom Python Exception with custom message?
- Can we throw an Unchecked Exception from a static block in java?
- How can we create a Service Provider interface in Java 9?
- How can we create an exception filter to handle unhandled exceptions in C# ASP.NET WebAPI?

Advertisements