When a programmer throws any custom exception, he must declare that execption in method signature.

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.

User defined exceptions

You can create your own exceptions in Java and they are known as user defined exceptions or custom exceptions.

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.

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

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……….]{    throw ex; }

Custom Checked and Custom Unchecked

  • 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.

Example: Custom Checked exception

Following Java program Demonstrates how to create Custom checked exception.

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 >= 'a' && ch

Chủ Đề