Finally

Finally

Many of the interview questions are aimed to make us pause. But, if you note those little pointers, it will be a cakewalk.

The finally block executes every time: if exception occurs, if it does not occur, if exception is handled, if it is not handled.

Take a look at the below example:


public class Main
{
? ? public static int getReturnValue(int r) {
? ? ? ? int returnVal = r;
? ? ? ? try {
? ? ? ? ? ? if(returnVal == 3) {
? ? ? ? ? ? ? ? throw new Exception("I am an exception");
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println("Return from try");
? ? ? ? ? ? return returnVal;
? ? ? ? }
? ? ? ? catch(Exception e) {
? ? ? ? ? ? returnVal = 0;
? ? ? ? ? ? System.out.println("Return from catch");
? ? ? ? ? ? return returnVal;
? ? ? ? }
? ? ? ? finally {
? ? ? ? ? ? returnVal = -1;
? ? ? ? ? ? System.out.println("Return from finally");
? ? ? ? ? ? return returnVal;
? ? ? ? }
? ? }
? ??
	public static void main(String[] args) {
		System.out.println(getReturnValue(1));
	}
}
        

        

In exception handling, the finally block always executes. Even if there are no exceptions, finally always executes.

Hence the above program always returns -1.

Finally can be used to add some really important code like cleaning up, closing resources etc.


要查看或添加评论,请登录

Preethi Pattabiraman的更多文章

  • Switch-Case

    Switch-Case

    There is nothing that helps a developer like a switch case statement. With multiple conditions and business logic to…

    2 条评论
  • MongoDB Operators

    MongoDB Operators

    MongoDB provides a wide range of intuitive operators that help us to query the collections for the relevant documents…

    1 条评论
  • Java Integer Cache

    Java Integer Cache

    I was astounded to learn about this feature in Java called the IntegerCache. A new functionality was added to reduce…

  • Circuit Breaker

    Circuit Breaker

    A microservice always needs its friends, the supporting microservices. They all collaborate to make an application…

    1 条评论
  • REST API - Content Negotiation

    REST API - Content Negotiation

    Please find part 1 of this series in the above link. Generally, REST resources can have multiple representations of the…

    1 条评论
  • REST API - Documentation

    REST API - Documentation

    There are some basic REST API features that are expected from any API, such as Documentation Content Negotiation I18N…

    9 条评论

社区洞察

其他会员也浏览了