Are the instances of Exception checked or unchecked exceptions 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.

There are two types of exceptions in Java.

  • Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
  • Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.

Exception hierarchy

In Java all exceptions are sub classes of the java.lang.Throwable class.

All the instances of the Throwable and Exception classes are checked exceptions and the instances if the RuntimeException class are run time exceptions.

For example if you create an user-defined exception by extending the Exception class this will be thrown at compile time.

Example

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
raja
Published on 07-Aug-2019 12:46:03
Advertisements