try-catch Block in Java

The try-catch block is used in Exception Handling in Java.


try Block, is used to enclose the code that might throw an exception. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must follow by a Catch block or Finally block or both. try must be used within the method.


catch Block is used to handle the Exception. It must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block.


Use of try-catch in Exception Handling

We will see, how can we use the try-catch block in exception handling. First, let’s understand the issue with Exception Handling.

Suppose we have a code of thousand lines and some exceptions occur in the middle of code somewhere. So if the exception is not handled then the rest of the code after exception will not execute.

So if the exception is not handled then the execution abrupt forcefully.

If you handle the exception then an exception will be reported and next code will be executed in normal flow. We use try catch block to handle the exception. let’s see this with a simple example.

The above code will throw the exception — Exception in thread “main” java.lang.ArithmeticException: / by zero


Selenium Testing Video Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.


So that code after like j=i/0; will not execute. This is the problem with the exception handling. To overcome this issue we need to use try-catch blocks. Now Let’s see how we can handle this errors using try catch blocks.


java.lang.ArithmeticException: / by zero
Unhandled Exception


In the above example, We can see we enclosed the code where the exception might be occurring inside the try block and put the solution inside the catch block, using this way we have reported the error our class was executed successfully.

So this is the application of try-catch block in the exception handling in Java.

You also can see the flow of try-catch block If an exception occurs in try block then the control of execution is passed to the catch block from try block. The exception is caught up by the corresponding catch block.


0 Comment

Leave a Reply