Mega Code Archive

 
Categories / Java Tutorial / Development
 

Error Handling

You can isolate code that may cause a runtime error using the try statement. try statement normally is accompanied by the catch and the finally statements. In case of an error, Java stops the processing of the try block and jump to the catch block. In the catch block, you can handle the error or notify the user by 'throwing' a java.lang.Exception object. Or you can re-throw the exception or a new Exception object back to the code that called the method. If a thrown exception is not caught, the application will stop abruptly. In the finally block, you write code that will be run whether or not an error has occurred. The finally block is optional. You can have more than one catch block. This is because the code can throw different types of exceptions. If the type of exception thrown does not match the exception type in the first catch block, the JVM goes to the next catch block and does the same thing until it finds a match. If no match is found, the exception object will be thrown to the method caller. If the caller does not put the offending code that calls the method in a try block, the program crashes. This is the syntax of the try statement. try {          [code that may throw an exception]      } catch (ExceptionType-1 e) {          [code that is executed when ExceptionType-1 is thrown]      } [catch (ExceptionType-2 e) {          [code that is executed when ExceptionType-2 is thrown]      }]        ...      } [catch (ExceptionType-n e) {          [code that is executed when ExceptionType-n is thrown]      }]      [finally {          [code that runs regardless of whether an exception was thrown]]      }]