Exceptions:
Exceptions are a set of mechanisms which are to be defined to do something when some problems happen during runtime. Some of the famous exceptions which occur normally are divide by zero exception and array out of bounds exceptions.
Java programming language has a great support for exception handling issues.
Exceptions are handled by using the try, catch ,throws and the finally statements.
The Try Block:
Use this block to enclose the area in the code which is exception prone.
The catch Block:
This block should immediately follow the try block. It contains the error message to be displayed and sometimes can be used to throw other exceptions.
Throws statement:
This statement is used to throw an exception .The exception can be predefined or user defined.
Finally Block:
This contains the set of statements which are to be executed no matter what kind of exception occurs in the program and is usually placed below the catch block.
Syntax:
function_name throws exception_name{//statements
try { //statements}
catch {//statements// may contain throws syntax in it as well}
finally {//statements that must be executed at all costs}
}
Exceptions can be checked or unchecked.
Checked exceptions are supposed to be handled by the programmer.
Unchecked exceptions are mainly due to bugs in the program or due to run time errors. Exceptions from which a program cannot escape at all are called errors. Errors make the program to just stop abruptly. Catch block should not be provided for errors.
Common Exceptions:
NullpointerException , securityException, NumberFormatException , FileNotFoundException etc.
User Defined exceptions can be created by Extending the exception class.
Public class userexpname extends Exception
{//statements}
To throw user defined exceptions You will have to use the throw clause.