try catch finally Java Blocks | Exception Handling Examples

Try catch and finally, Java block is used to handle an exception in programs. Each block has its own functionalities and important. This block helps in preventing ugly application crashes and make application robust.

try catch finally Java Blocks

There is always a chance application code that may throw exceptions in runtime and you have to handle the exception by executing alternate application logic to report back to the user.

About try catch finally Java Blocks:-

All bocks are written with a keyword followed by the curly braces.

  • try block – It contains the application code like reading a file, writing to databases or performing complex business operations.
  • catch block – It handles the checked exceptions thrown by try block as well as any possible unchecked exceptions.
  • finally block – Its an optional and typically used for closing files, network connections, etc. 

The flow of try catch finally java blocks

If there are no exceptions then the catch block will not call and finally, code will execute. Another condition if an exception will occur, then all blocks will be call.

On Exception or not, the next code line is work fine.

flow of try catch finally java blocks

Exception Handling Examples

Case 1: Without Exception

Output:

10.555555
finally block is always executed

Case 2: If the Exception occurs

Output:

java.lang.ArithmeticException: / by zero
finally block is always executed

Q: How to Java try finally without a catch block?

Answer: You can use java try and finally blocks without a catch. But you have to handle the error or depends on whether you can deal with the exceptions that can be raised at this point or not.

The finally block is typically used for closing files, network connections, etc. 

See below example of it:- With the exception.

Output:

 Java try finally without a catch block

Q: How to handle exception in finally block java?

Answer: Is there an elegant way to handle exceptions that are thrown in finally block?

Usually, do it like this:

Elsewhere:

Source: https://stackoverflow.com/questions/481446/throws-exception-in-finally-blocks

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java try, catch & finally blocks Example codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.