Java Program to Throw Exception

01. Example:

public class throwErrorExample {
    
   static void throwErrorMethod(int number) {
      if (number < 0){
         throw new ArithmeticException("There is something wrong.");
      }
      else{
         System.out.println("Check positive and negative number.");
      }
   }
   
   public static void main(String args[]) {
      throwErrorMethod(1);
      System.out.println("Start writing code from here.");
   }
   
}

Output:

Table of Contents

Check positive and negative number.
Start writing code from here.


02. Example:

public class throwErrorExample {
    
   static void throwErrorMethod(int number) {
      if (number < 0){
         throw new ArithmeticException("There is something wrong.");
      }
      else{
         System.out.println("Check positive and negative number.");
      }
   }
   
   public static void main(String args[]) {
      throwErrorMethod(-1);
      System.out.println("Start writing code from here.");
   }
   
}

Output:

Exception in thread "main" java.lang.ArithmeticException: There is something wrong.
	at throwErrorExample.throwErrorMethod(throwErrorExample.java:5)
	at throwErrorExample.main(throwErrorExample.java:13)

Leave a comment