JAVA | Explain the following terms w.r.t exception handling:

(1)   Try-catch
(2)   Throw
(3)   Throws
(4)   Finally

(1) Try-catch: Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java runtime system. A catch block immediately follows the try block. The catch block can have one or more statements that are necessary to process the exception.  
Syntax
try 
// block of code to monitor for errors
 }
catch (ExceptionType1 exOb)
// exception handler for ExceptionType1 

(2) Throw: It is mainly used to throw an instance of user defined exception. 
Example:
throw new myException(“Invalid number”);
assuming myException as a user defined exception.

(3) Throws: This keyword can be used along with method declaration with any exception so that each statement from that method is monitored for the errors and if there is any errors, then the system shows its own error message. Throws does not require separate try catch block to monitor the errors. 
Syntax:
datatype method() throws ExceptionType
{
//method body;
Example :
public static void main(String args[]) throws IOException 

(4)  Finally: 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. 
Syntax:
finally
{
// block of code to be executed before try block ends
}

Post a Comment

0 Comments