When a programmer throw an custom exception he must declare the exception in method signature mcq

An exception is an issue (run time error) that 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.

Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own Exception is known as a custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the ‘throw’ keyword.

For example, MyException in the below code extends the Exception class. 

Why use custom exceptions?

Java exceptions cover almost all the general types of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.

Following are a few of the reasons to use custom exceptions:

  • To catch and provide specific treatment to a subset of existing Java exceptions.
  • Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.

In order to create a custom exception, we need to extend the Exception class that belongs to java.lang package.

Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.

class MyException extends Exception {

    public MyException(String s)

    public static void main(String args[])

            throw new MyException("GeeksGeeks");

            System.out.println("Caught");

            System.out.println(ex.getMessage());

In the above code, the constructor of MyException requires a string as its argument. The string is passed to the parent class Exception’s constructor using super(). The constructor of the Exception class can also be called without a parameter and the call to super is not mandatory. 

class MyException extends Exception {

    public static void main(String args[])

            System.out.println("Caught");

            System.out.println(ex.getMessage());

This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. 


Article Tags :


Great Learning is an ed-tech company that offers impactful and industry-relevant programs in high-growth areas. With a strong presence across the globe, we have empowered 10,000+ learners from over 50 countries in achieving positive outcomes for their careers. Know More

Java 8Object Oriented ProgrammingProgramming

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 <= 'z')) {             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

On compiling, the above program generates 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 simply change the class that your custom exception inherits to RuntimeException it will be thrown at run time

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

If you run the previous program By replacing the NotProperNameException class with above piece of code and run it, it generates the following runtime exception.

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)

Updated on 03-Jul-2020 08:02:42

Neuester Beitrag

Stichworte