Exceptions are objects created by JVM that represent the corresponding logical errors. If we are able to handle those exceptions class object, we can prevent the program from getting terminated. Thus the concept of handling the exception class objects and avoiding them from the reaching block to the JVM is known as Exception Handling. We can handle the exception class objects by assigning them to the corresponding exception class references.
Procedure of handling the exceptions:
- We have two keywords try and catch to implement the exception handling.
- The try keyword recognizes the exception class objects created by the JVM and it gets hold of those objects and transfers them to the catch block.
- In the catch block we should be able to assign those objects to the appropriate references so that they will not reach JVM and therefore program would not be terminated.
Catch (Exception e1)
System. Out. Prinln (“exception in fun1 ()”);
System. Out. Prinln( e1);
- Thus as soon as an exception is raised the user would be easily known in which part of the program the logical error has occurred.
- System. Out. Prinln (e1); prints some message instead of printing the address contained in e1. This is because the exception class overrides the to -string method of the object class.
- In this way, we can use try and catch blocks in any part of the program.
- We can know in which part of the program the logical error has actually occurred.
- We are not allowing the JVM to terminate the entire program only the try block in which the error has occurred would be terminated.
- Syntax errors occurred whenever a statement written by the programmer cannot be compiled by the compiler.