Java Exception


Java Exception

Exceptions are the undesirable mistakes or bugs or occasions that confine the typical execution of a program. Each time an exception happens, program execution gets disturbed. A message is displayed on the console. The java.lang.Exception class is the parent class of all the exception classes. The Exception class, it is a subclass of the underlying Throwable class. Exception in Java is an occasion that interferes with the execution of program directions and disturbs the typical progression of program execution. It can be called as an object that wraps an error event data that happened within a method and it is passed to the runtime framework. In Java, exceptions are primarily utilized for demonstrating various kinds of error conditions.

Exception hierarchy is as shown below:

  • Throwable
  • Exception
    -Checked
    -Unchecked
  • Error
    -Virtual Machine error
    Assertion error
The two types of exceptions are listed below:


Checked Exceptions:

These exceptions are also called as compile-time exceptions as these type of exceptions are checked by the compiler during the compilation procedure to confirm whether the exception is handled by the programmer or not. Otherwise the system shows a compilation error.

Examples:

SQLException, IOException, InvocationTargetException, and ClassNotFoundException.

-

Unchecked Exceptions:

These exceptions are the exceptions that take place during the execution of the program, also referred to as Runtime exceptions. The exceptions are generally ignored during the compilation process. They are not checked during the compilation of the program.

Examples:

Errors during programming such as logical errors, and using incorrect APIs.

Example :

Com.knowledge2life public class Main { public static void main(String[] args) { try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println("Knowledge2life"); } } }

OUTPUT:

Knowledge2life