Java Programming

11.2 Try Catch

A method catches an exception using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception.

Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

The code which is prone to exceptions is placed in the try block, when an exception occurs, that exception occurred is handled by catch block associated with it.

Every try block should be immediately followed either by a class block or finally block.

Multiple catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

this is just an example of 3 catch statements you can have any number of them If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.

Syntax
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}

Download for more knowledge

https://play.google.com/store/apps/details?id=ab.java.programming

Leave a comment