Try catch block

// By:Team // No Comment

Email this to someonePrint this pageShare on Google+2Share on Facebook0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on StumbleUpon0

Five keywords used in Exception handling:

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

try block

Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.

Syntax of try catch block


 

Syntax of try with finally block


 

catch block

Catch block is used to handle the Exception. It must be used after the try block.

Problem without exception handling


 

 

 

As displayed in the above example, rest of the code is not executed i.e. rest of the code… statement is not printed. Let’s see what happens behind the scene:

What happens behind the code int a=50/0;

Try catch block in java

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:

  • Prints out exception description.
  • Prints the stack trace (Hierarchy of methods where the exception occurred).
  • Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.


Solution by exception handling

 

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code… statement is printed.

 

The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.

Example of throw keyword

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

 

 

Email this to someonePrint this pageShare on Google+2Share on Facebook0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on StumbleUpon0

About Team

Browse Archived Articles by Team

Related

Sorry. There are no related articles at this time.