- An Exception is an abnormal condition that arises during the execution of any program.
- An exception is a run-time error. In computer languages that do not support exception handling, errors of the program must be checked and handled manually.
- Java's exception handling avoids these problems by providing a wide range of exception classes.
- A java exception is an object that describes the exceptional (i.e., error) condition that has occurred in a program.
- When an exceptional condition arises, an object representing that exception is created and thrown to method that caused the error.
Java exception handling is managed by the following five keywords:
- try
- catch
- throw
- throws
- finally
The following is the basic block of simple exception handling in java:
try{
//Block of code to be monitored
}
catch(ExceptionType1Object ob){
//Exception handling code for ExceptionType1
}
catch(ExceptionType2Object ob){
//Exception handling code for ExceptionType2
}
.
.
.
finally{
//Block of code to be executed before try block ends
}
Basic description of the above block:
- The code / program statement to be monitored for exception are to be written in try block.
- If any exception occurs within try block, it is thrown and our code can catch that exception using catch block and handle it in some of the very user friendly manner.
- System generated exceptions are automatically thrown by the Java run-time system.
- To manually throw an exception, we can use the throw keyword.
- Any exception that is thrown out of a method must be specified using throws keyword.
- The finally block is a block is executed compulsory. A code which we want to be executed for sure whether exception occurs or not, like releasing resources, closing database connections, closing stream connections, etc, we can write that code in finally block.
No comments:
Post a Comment