Skip to main content

How to create custome exception in java || by Er prince kumar ojha

  How to create custome exception in java || by              Er prince kumar ojha

  ====================================================================This Java tutorial guides you on how to create your own exceptions in Java.In the article Getting Started with Exception Handling in Java, you know how to catch throw and catch exceptions which are defined by JDK such as IllegalArgumentExceptionIOExceptionNumberFormatException, etc.What if you want to throw your own exceptions? Imagine you’re writing a student management program and you want to throw StudentExceptionStudentNotFoundExceptionStudentStoreException and the like?So it’s time to create new exceptions of your own.We will call JDK’s exceptions built-in exceptions and call our own exceptions custom exceptions.Let me tell you this: Writing custom exceptions in Java is very easy, but the important thing is, you should ask yourself this question:







 1. Why do I need custom exceptions?Why do we need to create a new exception, instead of using the ones defined by JDK?The answer could be very simple: When you couldn’t find any relevant exceptions in the JDK, it’s time to create new ones of your own.But, how do we know which exception is relevant, which is not?
By looking at the names of the exceptions to see if its meaning is appropriate or not. For example, the IllegalArgumentException is appropriate to throw when checking parameters of a method; the IOException is appropriate to throw when reading/writing files.
From my experience, most of the cases we need custom exceptions for representing business exceptions which are, at a level higher than technical exceptions defined by JDK. For example: InvalidAgeExceptionLowScoreExceptionTooManyStudentsException, etc.
 
2. Writing your own exception class
Now, let’s see how to create a custom exception in action. Here are the steps:
  • Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.
  • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
  • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.
That’s it. The following is a custom exception class which is created by following the above steps:
1
2
3
4
5
6
public class StudentNotFoundException extends Exception {
 
    public StudentNotFoundException(String message) {
        super(message);
    }
}
And the following example shows the way a custom exception is used is nothing different than built-in exception:
1
2
3
4
5
6
7
8
9
10
11
public class StudentManager {
 
    public Student find(String studentID) throws StudentNotFoundException {
        if (studentID.equals("123456")) {
            return new Student();
        else {
            throw new StudentNotFoundException(
                "Could not find student with ID " + studentID);
        }
    }
}
And the following test program handles that exception:
1
2
3
4
5
6
7
8
9
10
11
12
13
public class StudentTest {
    public static void main(String[] args) {
        StudentManager manager = new StudentManager();
 
        try {
 
            Student student = manager.find("0000001");
 
        catch (StudentNotFoundException ex) {
            System.err.print(ex);
        }
    }
}
Run this program and you will see this output:
1
StudentNotFoundException: Could not find student with ID 0000001
 
3. Re-throwing an exception which is wrapped in a custom exception
It’s a common practice for catching a built-in exception and re-throwing it via a custom exception. To do so, let add a new constructor to our custom exception class. This constructor takes two parameters: the detail message and the cause of the exception. This constructor is implemented in the Exception class as following:
      public Exception(String message, Throwable cause)
Besides the detail message, this constructor takes a Throwable’s subclass which is the origin (cause) of the current exception. For example, create the StudentStoreException class as following:
1
2
3
4
5
6
public class StudentStoreException extends Exception {
 
    public StudentStoreException(String message, Throwable cause) {
        super(message, cause);
    }
}
And the following example shows where the StudentStoreException gets thrown:
1
2
3
4
5
6
7
public void save(Student student) throws StudentStoreException {
    try {
        // execute SQL statements..
    catch (SQLException ex) {
        throw new StudentStoreException("Failed to save student", ex);
    }
}
Here, suppose that the save() method stores the specified student information into a database using JDBC. The code can throw SQLException. We catch this exception and throw a new StudentStoreException which wraps the SQLException as its cause. And it’s obvious that the save() method declares to throw StudentStoreException instead of SQLException.
So what is the benefit of re-throwing exception like this?
Why not leave the original exception to be thrown?
Well, the main benefit of re-throwing exception by this manner is adding a higher abstraction layer for the exception handling, which results in more meaningful and readable API. Do you see StudentStoreException is more meaningful than SQLException, don’t you?
However, remember to include the original exception in order to preserve the cause so we won’t lose the trace when debugging the program when the exception occurred.
And the following code demonstrates handling the StudentStoreException above:
1
2
3
4
5
6
7
8
9
StudentManager manager = new StudentManager();
 
try {
 
    manager.save(new Student());
 
catch (StudentStoreException ex) {
    System.err.print(ex);
}
That’s about the lesson of writing custom exceptions in Java.
   

References:

Comments

Popular posts from this blog

How to Send OTP in Mobile Number | login with OTP mobile Number | How to send OTP in mobile no with Spring Boot APP

   ðŸ˜‚               Login with Mobile Number OTP ---------------------------------------------------------------------------- If you want to develop a project to log in with OTP mobile Number in Spring Boot Applications then this post for you. In this post, I am going to use some other service to send the OTP in mobile number. we have to use it in this project spring boot. we are going to use Twilio to send SMS. we are going to use a web socket to send the data from the browser to the SMS gateway. Oracle Database for store the user details. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.3.3.RELEASE</version> </dependency> <dependency> <groupId>com.twilio.sdk</grou

Spring Boot With MySQL Database connection with Examples | MySQl Database Configuration with Spring Boot Projects

 ðŸ˜ƒ MySQL Database Configuration with Spring Boot Projects  In this article, we are going to introduce How to connect MySQL Database with the Spring Boot project. pom.xml   <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</gro

How can we create Auto generated field or ID for mongodb using spring boot

😂 How can we create an Auto-generated field or ID for MongoDB using spring boot? First Create One Application Like Mongodb_sequence-id-generator Pom.XML <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> </dependency> User.java package com.app; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "users_db") public class User { @Transient public static final String SEQUENCE_NAME = &