try and catch block in java

In the previous block, we have seen What is Exception Handling? In this post, we will discuss about the try and catch block.

What is a try block?

A try block contains a set of programming statements where exception may occur. It is followed by a catch block which is used to capture the exception occurred in the try block. A try block must followed by catch block or finally block or both, otherwise it will throw a compile time error.

Syntax of try block:

What is a catch block?

A catch block must be associated a try block. If any particular exceptions occurs in try block, that exception will be handled by the catch block. The code for exception handling should be written in the catch block.

Syntax of catch Block:

Understand the problem without try-catch block:

Let’s take an example where we divide a number with 0.

Output: Exception in thread “main” java.lang.ArithmeticException: / by zero at com.test.SacnnerEx.main(SacnnerEx.java:11)

Observe the output above, we got an error “/ by zero”. But after that step code is not executed. Suppose, we don’t want to stop the execution of the program after error occurred, but requirement it should capture the error and execute rest of the code.

In that case, try-catch block will be helpful. Let’s how.

Output:
Error : / by zero
Caught the error
Important steps to be executed

In the above program , we have handled the exception in the catch block which is capturing the error. But rest of the code is also executed this time.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
What is Exception Handling in java?
Nested try block in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 8, 2015

    […] the previous post, we have seen try-catch block. In this post, we will discuss about the nested try […]