It is highly recomended to handle exceptions .
the code which may rise an exception is called risky code
and we have to define the inside the try block.
coressoponding handling code we have to define inside catch block.
try
{
Risky code
}
catch(Exception e)
{
Handling code
}
Without try block
class Test
{
public static void Main(String[] args)
{
System.out.println("State1");
System.out.println(10/0);
System.out.println("State3");
}
}
output
with try block
class Test
{
public static void Main(String[] args)
{
System.out.println("State1");
try
{
System.out.println(10/0);
}
catch(ArithmeticException e)
{
System.out.println(10/5);
}
System.out.println("State3");
}
}
try
{
Sate1;
Sate2;
Sate3;
}
catch(X e)
{
Sate4;
}
within the try block if anywhere exceptions rise then rest of the try block will not be executed even though we handle that exception .
if state 2 exception rise we cant get sate 3 as output
Hence within the try block we have to take risky code and the length of try block should as less as possible
example
if we type 1000 lines of code if we get first code exception then rest of the code will not execute
in addition, to try block there may be the chance of rising exception inside catch and finally blocks .
the way of handling an exception is varied from exception to exception .hence for every exception type it is highly recommended to take separate catch block.
that is .....try with multiple catch blocks is always possible and recommended to use
try
{
}
catch ArithmeticException e)
{
perform alternative arithmetic operators
}
catch (FileNotFoundException e)
{
use local file
}
catch (FileNotFoundException e)
{
use local file
}
This is the best way of programming practice.
Final
Finally
try
{
Risky code
}
catch(Exception e)
{
Handling code
}
finally
{
cleanup code
}
the specialty of finally block is it will be executed always respective whether exception rise or not whethert handle or not
Finalize()
that is catch without try invalid
0 Comments