How can an exception be thrown manually by a programmer in java?

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.

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

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

Throwing exceptions manually

You can throw a user defined exception or, a predefined exception explicitly using the throw keyword.

There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class.

To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.

Example

Following Java program throws a NullPointerException

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

Output

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

Whenever you throw an exception explicitly you need to make sure that the line with throw keyword is the last line of the program. This is because any code written after it is unreachable code and if you still have code snippets below this line a compile time error will be generated.

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");
   }
}

Compile time error

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

User defined exceptions

Usually the throw keyword is mostly used to throw user defined exception. Whenever we need to define your own exception you need to define a class extending the Throwable class, override the required methods.

Instantiate this class, throw it using the throw keyword wherever you want the exception.

Example

In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException.

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

Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables.

Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values.

In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24.

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

On executing this program, you need to pass name and age values from keyboard. If the given age value is not between 17 and 24 then 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)
raja
Published on 05-Aug-2019 18:17:07
Advertisements