World's most popular travel blog for travel bloggers.

What is exception? What are different types of exceptions? Explain need of exceptions
handling with the help of a program.

, , No Comments

 Exception: When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Types of Exception in Java with Examples

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. 
 

  1. ArithmeticException 
    It is thrown when an exceptional condition has occurred in an arithmetic operation.
  2. ArrayIndexOutOfBoundsException 
    It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
  3. ClassNotFoundException 
    This Exception is raised when we try to access a class whose definition is not found
  4. FileNotFoundException 
    This Exception is raised when a file is not accessible or does not open.
  5. IOException 
    It is thrown when an input-output operation failed or interrupted
  6. InterruptedException 
    It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
  7. NoSuchFieldException 
    It is thrown when a class does not contain the field (or variable) specified
  8. NoSuchMethodException 
    It is thrown when accessing a method which is not found.
  9. NullPointerException 
    This exception is raised when referring to the members of a null object. Null represents nothing
  10. NumberFormatException 
    This exception is raised when a method could not convert a string into a numeric format.
  11. RuntimeException 
    This represents any exception which occurs during runtime.
  12. StringIndexOutOfBoundsException 
    It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string

Exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.

class Main {
public static void main(String[] args) {

try {

// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}

Output

ArithmeticException => / by zero

0 comments:

Post a Comment

Let us know your responses and feedback