Home  >  Article  >  Java  >  Custom exceptions in Java

Custom exceptions in Java

王林
王林forward
2023-08-24 11:41:082061browse

Custom exceptions in Java

You can create your own exceptions in Java, they are called user-defined exceptions or custom exceptions.

To create user-defined exceptions, extend one of the above classes. To display a message, override the toString() method or call the superclass parameterized constructor by bypassing the message in string format.

MyException(String msg){
   super(msg);
}
Or,
public String toString(){
   return " MyException [Message of your exception]";
}

Then, in other classes that need to throw this exception, create an object of the created custom exception class and use the throw keyword to throw the exception.

MyException ex = new MyException ();
If(condition……….){
   throw ex;
}

Custom checked exceptions and custom unchecked exceptions

  • All exceptions must be subclasses of Throwable.

  • If you want to write a checked exception that is automatically enforced by a 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.

Example: Custom Checked Exception

The following Java program demonstrates how to create a custom checked exception.

Online demonstration

import java.util.Scanner;
class NotProperNameException extends Exception {
   NotProperNameException(String msg){
      super(msg);
   }
}
public class CustomCheckedException {
   private String name;
   private int age;
   public static boolean containsAlphabet(String name) {
      for (int i = 0; i < name.length(); i++) {
         char ch = name.charAt(i);
         if (!(ch >= &#39;a&#39; && ch <= &#39;z&#39;)) {
            return false;
         }
      }
      return true;
   }
   public CustomCheckedException(String name, int age){
      if(!containsAlphabet(name)&&name!=null) {
         String msg = "Improper name (Should contain only characters between a to z (all small))";
         NotProperNameException exName = new NotProperNameException(msg);
         throw exName;
      }
      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 person: ");
      String name = sc.next();
      System.out.println("Enter the age of the person: ");
      int age = sc.nextInt();
      CustomCheckedException obj = new CustomCheckedException(name, age);
      obj.display();
   }
}

Compile-time exception

When compiling, the above program will generate the following exception.

CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown
   throw exName;
   ^
1 error

Example: Custom Unchecked Exception

If you just change the class your custom exception inherits from to RuntimeException, it will be thrown at runtime

class NotProperNameException extends RuntimeException {
   NotProperNameException(String msg){
      super(msg);
   }
}

If you run the above program, replace the NotProperNameException class with the above code and run it, the following runtime exception will be generated.

Runtime exception

Enter the name of the person:
Krishna1234
Enter the age of the person:
20
Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
   at july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25)
   at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)

The above is the detailed content of Custom exceptions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete