Wednesday, December 12, 2018

Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

  1. try{  
  2. //code that may throw exception  
  3. }catch(Exception_class_Name ref){}  

Syntax of try-finally block

  1. try{  
  2. //code that may throw exception  
  3. }finally{}  

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block.

Rule: At a time only one Exception is occured and at a time only one catch block is executed.

Rule: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.


Java 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 follows try or catch block.


Why use java finally

  • Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.


Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

No comments:

Post a Comment