English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How does a programmer manually throw an exception in Java?

Exceptions are issues that occur during program execution (runtime errors). When an exception occurs, the program will terminate abruptly, and the code after the line where the exception occurred will never be executed.

Example

import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number:");
      int a = sc.nextInt();
      System.out.println("Enter second number:");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: ");+c);
   }
}

Output Result

Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)

manually throw an exception

You can usethrow The keyword explicitly throws user-defined or predefined exceptions.

There are two types of user-defined and predefined exceptions, each represented by a class and inheriting from the Throwable class.

To explicitly throw an exception, you need to instantiate its class and use the 'throw' keyword to throw its object.

Example

The following Java program throws NullPointerException

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

Output Result

Hello
Exception in thread "main" java.lang.NullPointerException
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6)

When an exception is explicitly thrown, it is necessary to ensure that the line with the 'throw' keyword is the last line of the program. This is because any code written after this is inaccessible code, and if you still have a code snippet below this line, a compilation error will occur.

Example

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
      System.out.println("How are you");
   }
}

Compilation error

D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
   System.out.println("How are you");
   ^
1 error

User-defined exceptions

The throw keyword is usually used to throw user-defined exceptions. Whenever we need to define our own exceptions, we need to define a class that extends the Throwable class and override the required methods.

Instantiate this class and use the throw keyword to throw it at any place where an exception is needed.

Example

In the following Java program, we will create a custom exception class named AgeDoesnotMatchException.

public class AgeDoesnotMatchException extends Exception {
   AgeDoesnotMatchException(String msg) {
      super(msg);
   }
}

Another class Student contains two private variables name and age, and a parameterized constructor to initialize instance variables.

As the main method, we accept the user's name and age value, and initialize the Student class by passing the accepted values.

In the constructor of the Student class, we create an exceptionAgeDoesnotMatchExceptionobjects, and the age value is between17to24between when an exception is triggered (using throws).

public class Student extends RuntimeException {
   private String name;
   private int age;
   public Student(String name, int age) {
      try {
         if (age <17|| age >24) {
            String msg = "Age is not between 17 and 24";
            AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg);
            throw ex;
         }
      } catch (AgeDoesnotMatchException e) {
         e.printStackTrace();
      }
      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 Student: ");
      String name = sc.next();
      System.out.println("Enter the age of the Student should be 17 to 24 (including 17 and 24): ");
      int age = sc.nextInt();
      Student obj = new Student(name, age);
      obj.display();
   }
}

Output Result

When executing this program, you need to pass the name and age values from the keyboard. If the given age value is not in17to24If the age is not between, an exception occurs as shown below-

Enter the name of the Student:
Krishna
Enter the age of the Student should be 17 to 24 (including 17 and 24):
14
AgeDoesnotMatchException: Age is not between 17 and 24
Name of the Student: Krishna'
Age of the Student: 14
   at Student.<init>(Student.java:18)
   at Student.main(Student.java:39)
You May Also Like