Exception basics

Exceptions are run times errors. During execution of program an exception is occurred which is thrown in form of object. That object represent that error.

Exception Types

Programmer of java experienced two type of errors in programs

1. Compile Time Error

Compiler time error occurred when there is a syntax error in program. For example if a variable is declared "a int;". Compile time error won't allow execution of program. If there is any wrong statement written that time also error will be reported by compiler during compilation. Compilation errors broadly include syntax and semantic errors.

2. Run Time Error

During execution time problem arises known as run time errors. Run time errors also known as exceptions. Run time errors are following

  1. Wrong input given by user
  2. File doesn't exist on which read operation has to be performed.
  3. Try to divide by zero

All exceptions extends Throwable class. Throwable is parent class for all the exceptions. Throwable has two sub classes Exception and Error. Exception class represent run time error which are supposed to be caught. Another class Error represent error related to run time environment.

What happen if there is an exception in the program?

Program with error:

class exp 
public static void main(String arg[])
int b=0;
int a=4/b;
System.out.println("End of program");

Execution of above program will result in following:

Error Exception in thread "main" java.lang.ArithmeticException: / by zero
at exp.main(exp.java:6)

During execution when 4/b statement is executed, exception is generated. Exception must be handled by exception handler. If there is no exception handler in program then exception will be handled by handler provided by compiler. Default exception handler will terminate the program at line number 6 and print details of exception.

"Exception in thread 'main'" meaning of this message is exception occurred in main thread. Every program has one thread "main". In our program exception is inside main method. Main method start the main thread that's why exception is occurred in main thread. "java.lang.ArithmeticException: / by zero it specify type of exception. Second line in error message at exp.main(exp.java:6) specifying the statement which cause the exception.

Exception in java can be handled in using try, catch, throw, throws and finally.