Showing posts with label Java exception handling. Show all posts
Showing posts with label Java exception handling. Show all posts

Friday, August 23, 2024

Creating Custom Exception Class in Java

In this post we'll see how to create a custom exception in Java.

custom exception in Java

Though Java's exception handling covers the whole gamut of errors and most of the time it is recommended that you should go with standard exceptions rather than creating your own custom exception classes in Java, but you might need to create custom exception types to handle situations which are specific to your application.

Friday, May 31, 2024

Java Exception Handling Interview Questions And Answers

In this post interview questions and answers for exception handling in Java are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is Exception Handling?

    Exception Handling in Java provides a way to handle a situation when an exception is thrown and shows a meaningful message to the user and continue with the flow of the program.

    When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

    The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.

    Five keywords used to manage Java exception handling

    • try- Any code that might throw an exception is enclosed within a try block.
    • catch- If an exception occurs in try block, catch block can provide exception handlers to handle it in a rational manner.
    • finally- The finally block always executes when the try block exits. So, any code that must execute after a try block is completed should be put in finally block.
    • throw- throw is used to manually thrown an exception.
    • throws- Any exception that is thrown in a method but not handled there must be specified in a throws clause.
    Read more about Exception handling in Java here.

  2. Explain the exception hierarchy in Java?

    Throwable class is the super class of all the exception types. Below Throwable class there are two subclasses which denotes two distinct branches of exceptions-

    • Exception- An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.
    • Error- It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
      Examples of error are StackOverflowError, OutOfMemoryError etc.
    • Below Exception there is a distinct subclass RunTimeExcpetion- RunTimeExcpetion and its descendants denote the exceptional conditions that are external to the application, and the application usually cannot anticipate or recover from them.

    Read more about exception hierarchy in Java here.

  3. What is the difference between Checked Exception and Unchecked Exception?

    Checked Exception is a direct subclass of Exception where as unchecked exception is a subclass of RunTimeException.

    Checked exception should be wrapped in a try-catch block or specified as throws clause where as there is no such requirement for unchecked exception.

    Failure to provide exception handling mechanism for checked exception result in compiler error whereas no compile time error for unchecked exception.

    Checked exceptions are designed to reduce the number of exceptions which are not properly handled and where there is a reasonable chance for recovery. UnCheckedExceptions are mostly programming errors.

    Read more about difference between Checked Exception and Unchecked Exception here.

  4. What is the difference between error and exception?

    Exception- An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.

    Error- It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
    Examples of error are StackOverflowError, OutOfMemoryError etc.


  5. Is it necessary that each try block must be followed by a catch block?

    No it is not mandatory that there should be a catch block after a try block. try block can have only a matching finally block. So there are these valid combinations try-catch-finally, try-catch, try-finally.

    Read more about try-catch block here.

  6. What is finally block?

    When an exception occurs in the code, the flow of the execution may change or even end abruptly. That may cause problem if some resources were opened in the method.
    For example, if a file was opened in a method and it was not closed in the end as some exception occurred then the resources may remain open consuming memory. finally provides that exception-handling mechanism to clean up.

    Code with in the finally block will be executed after a try/catch block has completed. The finally block will be executed whether or not an exception is thrown.

    Read more about finally block here.

  7. Is it possible to have a finally block without catch?

    Yes we can have a try-finally block, catch is optional. We can have these combinations try-catch-finally, try-catch, try-finally.

    Read more about finally block here.

  8. Are you aware of any scenario when finally will not be executed?

    According to Java docs. If the JVM exits (By explicitly using System.exit() or a JVM crash) while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    Read more about finally here.

  9. What is a nested try statement?

    A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement.

    public class NestedTryDemo {
      public static void main(String[] args) {
        try{
          System.out.println("In Outer try block");
          try{
            System.out.println("In Inner try block");
            int a = 7 / 0;
          }catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException caught");
          }finally{
            System.out.println("In Inner finally");
          }
        }catch (ArithmeticException e) {
          System.out.println("ArithmeticException caught");
        }finally {
          System.out.println("In Outer finally");
        }
      }
    }
    
    Read more about nested try statement here.

  10. What are multiple catch blocks?

    There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, two or more catch clauses can be specified where each catch clause catches a different type of exception. When an exception is thrown, each of the catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.

    int a[] = {0};
    try{
      int b = 7/a[i];
    }catch(ArithmeticException aExp){
      aExp.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException aiExp){
      aiExp.printStackTrace();
    }
    
    Read more about multiple catch blocks here.

  11. What is exception propagation?

    When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.
    The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.
    If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation.

    Read more about exception propagation here.

  12. What is throw keyword?

    It is possible for a Java program to throw an exception explicitly that is done using the throw statement.

    The general form of throw is-
    throw throwableObject;

    We can get this throwableObject in 2 ways-
    • By using the Exception parameter of catch block.
    • Create a new one using the new operator.
    try{
       throw new NullPointerException();   
      }catch(NullPointerException nExp){
       System.out.println("Exception caught in catch block of displayValue");
       throw nExp;
      }
     }
    
    Read more about throw keyword here.

  13. What is throws clause?

    If in a method we don't want to handle any exception but want to leave it to the calling method to handle any exception that is thrown by the called method, it is done using throws keyword.

    Using throws a method can just declare the exception it may throw and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws).

    General form of a method declaration that includes a throws clause

    type method-name(parameter-list) throws exception-list
    {
    // body of method
    }
    
    Here, exception-list is a comma-separated list of the exceptions that a method can throw.
    Read more about throws clause here.

  14. Difference between throw and throws?

    • throw is used to throw an exception.
    • throws is used to declare an exception, in the method signature, that can be thrown from a method.
    Read more about difference between throw and throws here.

  15. final Vs finally Vs finalize

    • final- final keyword is used to restrict in some way. It can be used with variables, methods and classes. When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank final variable, which must be initialized in the constructor.
      If you make a method final in Java, that method can't be overridden in a sub class.
      If a class is declared as final then it can not be sub classed.
    • finally- finally is part of exception handling mechanism in Java. finally block is used with try-catch block. finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc.
    • finalize()- finalize() method is a protected method of java.lang.Object class. Since it is in Object class thus it is inherited by every class. This method is called by garbage collector thread before removing an object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object final chance to cleanup before getting garbage collected.
      protected void finalize() throws Throwable
      {
        //resource clean up operations
      }
      
    Read more about final Vs finally Vs finalize here.

  16. What are the rules of exception handling with respect to method overriding?

    There are certain restrictions while overriding a method in case of exception handling in Java. Broadly there are two rules-

    • If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.
    • If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
      • sub-class can declare the same exception as declared in the super-class method.
      • subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
      • subclass method can choose not to declare any exception at all.
    Read more about exception handling and method overriding here.

  17. What is the error in the following code?

    class Parent{
       public void displayMsg() throws IOException{
         System.out.println("In Parent displayMsg()");
        throw new IOException("Problem in method - displayMsg - Parent");
       }
    }
    public class ExceptionOverrideDemo extends Parent{
      public void displayMsg() throws Exception{  
        System.out.println("In ExceptionOverrideDemo displayMsg()"); 
        throw new Exception("Problem in method - displayMsg - ExceptionOverrideDemo");
      }  
    }
     

    Here parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is wrong according to the rules of method overriding and exception handling. Thus the code will give compiler error.

    Read more about exception handling and method overriding here.

  18. What is multi-catch statement in Java 7?

    Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.

    catch(IOException exp){
      logger.error(exp);
      throw exp;
    }catch(SQLException exp){
      logger.error(exp);
      throw exp;
    }
    

    With Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol (|).

    catch(IOException | SQLException exp){
      logger.error(exp);
      throw exp;
    }
    
    Read more about multi-catch statement in Java 7 here.

  19. What is try-with-resources or ARM in Java 7?

    Java 7 introduced a new form of try known as try-with-resources for Automatic Resource Management (ARM). Here resource is an object that must be closed after the program is finished with it. Example of resources would be an opened file handle or database connection etc.

    Before the introduction of try-with-resources we had to explicitly close the resources once the try block completes normally or abruptly.

    try {
        br = new BufferedReader(new FileReader("C:\\test.txt"));
        System.out.println(br.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
      try {
        if (br != null){
          System.out.println("Closing the file");
          br.close();
        }                
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    

    try-with-resources helps in reducing such boiler plate code. Let's see the same example using try-with-resources.

    try(BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt"))) {            
      System.out.println(br.readLine());
    } catch (IOException e) {
      e.printStackTrace();
    } 
    
    Read more about try-with-resources in Java 7 here.

  20. When is custom exception class needed? How to create a custom exception class?

    According to Java Docs, you should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

    • Do you need an exception type that isn't represented by those in the Java platform?
    • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
    • Does your code throw more than one related exception?
    • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
    Read more about creating custom exception class here.

  21. What is the difference Between StackOverflowError and OutOfMemoryError in Java?

    StackOverflowError- Whenever you run any Java program even if you don’t explicitly create any thread a main thread is started and that thread runs the program. For each thread JVM creates a stack, whenever any method is invoked a new frame is created and pushed into the JVM stack for the thread. Each frame stores data corresponding to the invoked method including local variables, operand stack and a reference to the run-time constant pool and reference to exception table. Once the method execution is completed corresponding stack frame is popped out of the stack.
    JVM throws StackOverflowError if the stack memory requirement of any method exceeds the permitted stack memory size.

    OutOfMemoryError- In Java, memory for each object, for arrays and for instance variables (variables at class level not method level) is created on the heap. When there are no references to an object that object is garbage collected thus clearing the heap memory. If you try to create an object or array that tries to take more memory than the allocated heap memory or there are a lot of objects in heap that are still referenced so can’t be garbage collected and JVM tries to allocate heap memory for a new object JVM throws java.lang.OutOfMemoryError because there is no sufficient heap memory.

    Read more about difference Between StackOverflowError and OutOfMemoryError here.

Related Topics

  1. Java Multithreading Interview Questions And Answers
  2. Java Collections Interview Questions And Answers
  3. Java String Interview Questions And Answers
  4. Core Java Basics Interview Questions And Answers
  5. Java OOP Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Tuesday, April 23, 2024

Difference Between StackOverflowError and OutOfMemoryError in Java

Differences between StackOverflowError and OutOfMemoryError in Java is a frequently asked Java interview question. You may also encounter one of these errors in your application. Before going into StackOverflowError Vs OutOfMemoryError let’s get some background about these errors.


StackOverflowError in Java

Whenever you run any Java program even if you don’t explicitly create any thread a main thread is started and that thread runs the program.

For each thread JVM creates a stack, whenever any method is invoked a new frame is created and pushed into the JVM stack for the thread. Each frame stores data corresponding to the invoked method including local variables, operand stack and a reference to the run-time constant pool and reference to exception table.

Once the method execution is completed corresponding stack frame is popped out of the stack.

JVM throws StackOverflowError if the stack memory requirement of any method exceeds the permitted stack memory size. A very common scenario where you may see StackOverflowError is when you have a recursive method with no terminating condition. For example following program that calculates factorial of a number using recursive method call. Since there is no exit condition defined so recursive method call never ends resulting in StackOverflowError.

public class StackOFErrorExp {
  public static void main(String[] args) {
    double factorialResult = factorial(1000);
    System.out.println(factorialResult);
  }
  private static int factorial(int i) {
    /*
     * if (i == 0 || i == 1 ) '
     *  return 1;
     */
    return i * factorial(i - 1);
  }
}

OutOfMemoryError in Java

In Java, memory for each object, for arrays and for instance variables (variables at class level not method level) is created on the heap. When there are no references to an object that object is garbage collected thus clearing the heap memory.

If you try to create an object or array that tries to take more memory than the allocated heap memory or there are a lot of objects in heap that are still referenced so can’t be garbage collected and JVM tries to allocate heap memory for a new object JVM throws java.lang.OutOfMemoryError because there is no sufficient heap memory.

Here is an example of java.lang.OutOfMemoryError where objects are added to an ArrayList in an infinite loop. Since objects stored to the List are not garbage collected so heap memoery will finally run out of memory resulting in OutOfMemoryError.

public class OutofMemoryExp {
  public static void main(String[] args) {
    List list = new ArrayList<>();
    int i = 0;
    // results in indefinite loop
    while(true) {
      i++;
      list.add(i * 1000000);
    }  
  }
}

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at java.base/java.util.Arrays.copyOf(Arrays.java:3721)
 at java.base/java.util.Arrays.copyOf(Arrays.java:3690)
 at java.base/java.util.ArrayList.grow(ArrayList.java:237)
 at java.base/java.util.ArrayList.grow(ArrayList.java:242)
 at java.base/java.util.ArrayList.add(ArrayList.java:485)
 at java.base/java.util.ArrayList.add(ArrayList.java:498)
 at org.netjs.examples.OutofMemoryExp.main(OutofMemoryExp.java:14)

StackOverflowError Vs OutOfMemoryError in Java

  1. StackOverflowError is thrown when there is no sufficient stack space for storing method data.
    OutOfMemoryError is thrown when no sufficient heap space left for creating new objects or requested array size is more than heap memory.
  2. StackOverflowError happens when you have Recursive methods with out terminating condition.
    OutOfMemoryError happens when new objects can’t be allocated on the heap as existing objects still have references so can’t be garbage collected.
  3. In order to avoid StackOverflowError ensure that methods are finishing their execution and corresponding stack memory is freed.
    In order to avoid OutOfMemoryError ensure that there are no references to objects which you don’t need anymore so that such objects can be garbage collected freeing heap memory in the process.

That's all for this topic Difference Between StackOverflowError and OutOfMemoryError in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between Checked And Unchecked Exceptions in Java
  2. Difference Between throw And throws in Java
  3. final Vs finally Vs finalize in Java
  4. java.lang.ClassCastException - Resolving ClassCastException in Java
  5. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java

You may also like-

  1. Java Exception Handling Interview Questions And Answers
  2. Array in Java With Examples
  3. Varargs (Variable-length Arguments) in Java
  4. Type Erasure in Java Generics
  5. Pre-defined Functional Interfaces in Java
  6. Linear Search (Sequential Search) Java Program
  7. Introduction to Node.js
  8. Bean Scopes in Spring With Examples

Thursday, March 7, 2024

Multi-Catch Statement in Java Exception Handling

There has always been criticism of checked exceptions in Java exception handling for being verbose and cluttering the code with try-catch blocks.
In Java 7 two new features- try-with-resources (Automatic resource management) and multi-catch statement have been added to mitigate that problem to certain extent.

In this post we'll talk about multi-catch statement in Java exception handling along with examples to see how to handle multiple exceptions in a single catch block using multi-catch statement.

Handling more than one type of exception without multi-catch statement

Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.

catch(IOException exp){
  logger.error(exp);
  throw exp;
}catch(SQLException exp){
  logger.error(exp);
  throw exp;
}

It can be noted here that; though the catch blocks are having the same exception handling code, it is difficult to create a common catch block to eliminate duplicate code because variable exp has different types in both of the catch block.

Java multi-catch - Handling more than one type of exception

Java 7 onward it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by a pipe symbol (|).

catch(IOException | SQLException exp){
  logger.error(exp);
  throw exp;
}

Note that if a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter exp is final therefore you cannot assign any values to it within the catch block.

Java Multi-catch statement means better code

According to JavaDoc- "Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers."

Multi-catch statement & Exception hierarchy

While using multi-catch statement you will have to keep in mind the following rule.

If you specify two or more exceptions of the same hierarchy in the multi-catch statement, it will result in compile time error.
For example, following catch statement gives compiler error because FileNotFoundException is a subtype of the IOException class.

catch (FileNotFoundException | IOException ex) {    
 Logger.error(ex);   
}

Or the following statement, which also results in compile time error as Exception is super type of both ArithmeticException and ArrayIndexOutOfBoundsException.

// This will give compiler error
catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex){
  ex.printStackTrace();
}

Points to note

  1. With multi-catch statement in Java it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code.
  2. Each exception type within the multi-catch statement is separated by Pipe symbol (|).
  3. Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each.
  4. Specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.

That's all for this topic Multi-Catch Statement in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Try-With-Resources in Java With Examples
  2. Multiple Catch Blocks in Java Exception Handling
  3. Difference Between Checked And Unchecked Exceptions in Java
  4. Difference Between throw And throws in Java
  5. final Vs finally Vs finalize in Java

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Why Class Name And File Name Should be Same in Java
  3. Marker Interface in Java
  4. Difference Between Abstract Class And Interface in Java
  5. BigDecimal in Java With Examples
  6. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  7. Deadlock in Java Multi-Threading
  8. Java Stream API Tutorial

Monday, January 16, 2023

Difference Between Checked And Unchecked Exceptions in Java

Before going into the differences between checked and unchecked exceptions in Java let's first see what these two types of exceptions are.


Checked Exception in Java

As we know from the exception hierarchy, Throwable is the parent class of all the Exception types. Immediately below Throwable there is a subclass called Exception. This Exception class has one subclass called RunTimeException.

difference between checked and unchecked exception in Java

If an exception is a subclass of Exception but does not inherit from RuntimeException, it is a checked exception. The restriction with a checked exception is that it needs to be either caught in a method (with in a try-catch block), or the method needs to specify that exception in a throws clause declaration.

Checked exception classes in Java

  • IOException
  • FileNotFoundException
  • ParseException
  • ClassNotFoundException
  • CloneNotSupportedException
  • InstantiationException
  • InterruptedException
  • NoSuchMethodException
  • NoSuchFieldException

Unchecked Exception in Java

With in the exception hierarchy if an exception is a subclass of RuntimeException, it is an unchecked exception. An unchecked exception can also be caught by wrapping the code in try-catch block, but it does not have to as it is not verified at compile time. Thus the name 'unchecked'.

Most of the times these exceptions occur due to the programming errors. Unchecked exceptions can be thought of arising due to not having a proper testability condition with in a program. Take the following 3 examples.

  • NullPointerException- If already tested for null using if condition it won't arise.
  • ArrayIndexOutOfBoundsException- If already tested for length of an array it won't arise.
  • ClassCastException- if already checked using instanceof operator it won't arise.

Java's unchecked exceptions

  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • IllegalArgumentException
  • IllegalStateException
  • NullPointerException
  • NumberFormatException
  • AssertionError
  • ExceptionInInitializerError
  • StackOverflowError
  • NoClassDefFoundError

Checked Vs Unchecked exception in Java

Now when we know what are checked and unchecked exceptions, it is easy to list out the differences between checked and unchecked exceptions in Java.

  • Checked Exception is a direct subclass of Exception where as unchecked exception is a subclass of RunTimeException.
  • Checked exception should be wrapped in a try-catch block or specified as throws clause where as there is no such requirement for unchecked exception.
  • Failure to provide exception handling mechanism for checked exception result in compiler error whereas no compile time error for unchecked exception.
  • Checked exceptions are designed to reduce the number of exceptions which are not properly handled and where there is a reasonable chance for recovery. UnCheckedExceptions are mostly programming errors.

Usage of checked exception in Java

There is a lot of debate over whether checked exceptions are at all needed or not. General complain is that having checked exceptions result in a lot of boiler plate code. That problem has been recognized and Java7 has a feature called multi-catch statement to reduce exception handling code.

For checked exceptions Java language Specification says; "This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled".

Checked Exceptions should be used to declare expected errors from which there are chances to recover from. It doesn't make sense telling callers to anticipate exceptions that they cannot recover from.

As example If a user attempts to read from a non-existing file, the caller can prompt him for a new filename. On the other hand, if the method fails due to a programming bug (invalid input parameters or incorrect method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.

Why unchecked exception

According to the Java Language Specification "run-time exception classes are exempted because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in exceptions at run time. The information available to a Java compiler, and the level of analysis a compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers."

Proper usage of Unchecked Exception

One of the best practices for the exception handling is to preserve loose coupling. According to that an implementation specific checked exception should not propagate to another layer. As Exp. SQL exception from the DataAccessCode (DAO layer) should not propagate to the service (Business) layer. The general practice in that case is to convert database specific SQLException into an unchecked exception and throw it.

catch(SQLException ex){
    throw new RuntimeException("DB error", ex);

Points to note-

  • Checked exception classes are direct descendant of Exception class.
  • Unchecked exception classes are direct descendant of RunTimeException class, where RunTimeException class is the sub class of Exception class.
  • Checked exception must be handled either using try-catch block or declared using throws, not doing that will result in compile time error.
  • Not handling unchecked exception does not result in compile time error.
  • RunTime and Checked exceptions are functionally equivalent, whatever handling or recovery checked exceptions can do, runtime exceptions can also do. For checked exceptions it has been made sure (forced) that handling is there by making it a compile time error.

That's all for this topic Difference Between Checked And Unchecked Exceptions in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. final Vs finally Vs finalize in Java
  2. Try-With-Resources in Java With Examples
  3. Nested Try Statements in Java Exception Handling
  4. Best Practices For Exception Handling in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. static Import in Java With Examples
  2. Method overloading in Java
  3. Varargs (Variable-length Arguments) in Java
  4. How HashMap Works Internally in Java
  5. equals() And hashCode() Methods in Java
  6. Race Condition in Java Multi-Threading
  7. How to Create PDF From XML Using Apache FOP
  8. Java Lambda Expression And Variable Scope

Friday, December 23, 2022

Difference Between throw And throws in Java

In this post we'll see the difference between throw and throws keyword in Java which are used in Java exception handling. These two keywords, though look similar, are functionality wise very different

  • throw is used to throw an exception.
  • throws is used to declare an exception, that can be thrown from a method, in the method signature.

throw Vs throws in Java

  1. We can declare multiple exceptions as a comma separated list with throws statement.
    We can throw only one exception using throw keyword in Java.

    throws Example

    public void displayFile() throws IOException, ArithmeticException
    

    throw Example

    throw new NullPointerException();
    throw new FileNotFoundException();
    
  2. throw keyword in Java is followed by an object of the Exception class.
    throws is followed by exception class names themselves.

    throw Example

    catch(FileNotFoundException fExp){   
     // throwing fExp which is an object of FileNotFoundException type
     throw fExp;
    }
    
    // creating object and throwing
    throw new FileNotFoundException();
    

    throws Example

    public void displayFile() throws IOException, ArithmeticException
    

    It can be seen that Exception class name itself is in the declaration.

  3. throws clause in Java is used to declare an exception in the signature of the method where as throw keyword is used to throw an exception explicitly with in the code of the method or from a static block.

    throw from a static block

    static int i;
    static int b;
    static {
     System.out.println("in static block");
     try{
      i = 5;
      b = i * 5;
     }catch(Exception exp){
      System.out.println("Exception while initializing" + exp.getMessage());
      throw exp;
     }
     //System.out.println("Values " + i + " " +  b);
    }
    
  4. throws clause is used to declare that the method may throw the declared exceptions and calling method should provide the exception handling code.
    throw actually throws the exception and the run time system goes through the method hierarchy to search for a method that can handle the exception.

That's all for this topic Difference Between throw And throws in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. throws Keyword in Java Exception Handling
  2. Java Exception Handling And Method Overriding
  3. Exception Propagation in Java Exception Handling
  4. Nested Try Statements in Java Exception Handling
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Encapsulation in Java
  2. Difference Between Abstract Class And Interface in Java
  3. Constructor overloading in Java
  4. static Import in Java With Examples
  5. How ArrayList Works Internally in Java
  6. Can we start the same thread twice in Java
  7. interface default methods in Java 8
  8. Method Reference in Java

Wednesday, December 7, 2022

final Vs finally Vs finalize in Java

What are the differences among final, finally and finalize in java is one question asked a lot in Java interviews. This question is asked more to confuse a candidate as they all sound similar and of course by asking this question you get to assess the knowledge of the candidate about three things final, finally and finalize in Java!

Apart from having ‘final’ in all of these there is no similarity. Though it can be said that primary job of both finally and finalize is to clean up, so there is some similarity in functionality between finally and finalize.

So let’s go through differences among final, finally and finalize in Java.

final Vs finally Vs finalize in Java

final– final keyword in Java is used to restrict in some way. It can be used with variables, methods and classes.
When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank final variable, which must be initialized in the constructor.
If you make a method final in Java, that method can’t be overridden  in a sub class.
If a class is declared as final then it can not be sub classed.

Refer final in Java for detailed information about final.

finally– finally is part of exception handling mechanism in Java, finally block is used with try-catch block. Along with a try block we can have both catch and finally blocks or any one of them. So we can have any of these combinations- try-catch-finally, try-catch, try-finally.
finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc.
From Java 7 onwards try with resources provide another way to automatically manage resources.

try {
  // code that may throw an exception
} catch (Exception e) {
  // catch exception
} finally {
  //This block is always executed
  // so close any open resources here
}

Refer finally block in Java for detailed information about finally.

finalize()- finalize() method is a protected method of java.lang.Object class. Since it is in Object class thus it is inherited by every class. This method is called by garbage collector thread before removing an object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object final chance to cleanup before getting garbage collected.

protected void finalize() throws Throwable
{
  //resource clean up operations
}

Please note that it is not a good idea to rely on finalize() method for closing resources as there is no guarantee when finalize() method will be called by Garbage collector.

Refer finalize method in Java for detailed information about finalize.

That's all for this topic final Vs finally Vs finalize in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between Checked And Unchecked Exceptions in Java
  2. Java Exception Handling Tutorial
  3. Multi-Catch Statement in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Interface Default Methods in Java
  2. Difference Between Abstract Class And Interface in Java
  3. static Import in Java With Examples
  4. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  5. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  6. How HashMap Internally Works in Java
  7. Difference Between Comparable and Comparator in Java
  8. Java ReentrantLock With Examples

Friday, September 16, 2022

java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java

In this article we’ll see what is java.lang.ClassNotFoundException and how to resolve ClassNotFoundException in Java.

ClassNotFoundException in Java

ClassNotFoundException is a child class of Exception class. Being a descendant of Exception class also makes it a checked exception that means it needs to be either caught in a method (with in a try-catch block), or the method needs to specify that exception in a throws clause declaration.

When is ClassNotFoundException thrown

ClassNotFoundException is thrown when a Java application tries to load in a class through its string name but definition for the class with the specified name could not be found.

Methods that can be used for loading a class through its String name are as following-

  • The Class.forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

ClassNotFoundException is thrown at runtime since classloader tries to load the class at runtime using the String name.

Java ClassNotFoundException example

As the name of the exception itself suggests this exception is thrown when the class that has to be loaded is not found. One scenario where you may find this exception is if you try to load JDBC drivers using Class.forName() but the required jar is not in the classpath.

I have also encountered ClassNotFoundException when upgrading to new version of jar in my system and using some new classes available in that jar but not upgrading the jar in the Test server or production. With that you get the scenario which is often quoted by the developers “In my system it is working fine”!!!

For example following program tries to load Oracle driver but the required ojdbcxx.jar is not present in the classpath.

public class JDBCCon {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("oracle.jdbc.driver.OracleDriver");

      // Creating connection
      connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
                   "root", "admin");

      // creating Statement
      Statement stmt = connection.createStatement();  

      // Executing Query
      ResultSet rs = stmt.executeQuery("Select * from Employee");

      // Processing Resultset
      while(rs.next()){
        System.out.println("id : " + rs.getInt("id") + " Name : " 
          + rs.getString("name") + " Age : " + rs.getInt("age")); 
      }
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

Output

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
 at java.base/java.lang.Class.forName0(Native Method)
 at java.base/java.lang.Class.forName(Class.java:332)
 at org.netjs.prgrm.JDBCCon.main(JDBCCon.java:16)

As evident from the exception stack trace OracleDriver is not found so the ClassNotFoundException is thrown.

Resolving ClassNotFoundException in Java

As seen in the above example it is easy to see from the error log or exception stacktrace which class is causing the exception. Then you need to check whether the required jar (where the class resides) is present in the classpath or not.

If jar is there then ensure that you have the correct version and the class you are trying to load is part of that jar version.

If you are packaging your application and putting that jar or war in a server or another system to run make sure that all the classes are packaged properly and there are no omissions.

If class is there in the classpath then do ensure that there is no classpath change as part of some startup script.

That's all for this topic java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  2. Difference Between throw And throws in Java
  3. Multi-Catch Statement in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. intern() Method in Java String
  2. Private Methods in Java Interface
  3. Java Program to Convert a File to Byte Array
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. ConcurrentSkipListMap in Java
  6. Spring MVC Example With @PathVariable - Creating Dynamic URL
  7. Spring Web Reactive - Spring WebFlux Example Using Annotation-Based Programming
  8. Python Installation on Windows

Saturday, August 20, 2022

java.lang.ClassCastException - Resolving ClassCastException in Java

In this article we’ll see what is java.lang.ClassCastException and how to resolve ClassCastException in Java.

ClassCastException in Java

ClassCastException is thrown in a Java application when you try to cast an object to a class of which the original object is not an instance i.e. if the class of which you have an object and the class you are trying to cast that object to are not having a parent-child relationship then casting to that class will result in ClassCastException.

Exception hierarchy for the ClassCastException in Java is as follows-

ClassCastException in Java

Since ClassCastException derives from RuntimeException that means it is an unchecked exception and there is no need to explicitly handle it using try-catch block.

ClassCastException is closely associated to how type casting is done. You can refer this post Type Casting in Java to get better understanding of type casting in Java.

ClassCastException was quite frequently seen before Java generics came into the picture. When collections were not type safe and you needed to explicit cast the elements when retrieving them from the collection was the fertile ground for the ClassCastException.

ClassCastException Java example

This example shows a scenario where ClassCastException is thrown. Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment and CardPayment implementing the Payment interface.

Payment interface

public interface Payment {
 public boolean proceessPayment(double amount);
}

CashPayment class

import org.netjs.examples.interfaces.Payment;

public class CashPayment implements Payment {
 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Cash payment done for Rs. " + amount);
  return true;
 }
}

CardPayment class

import org.netjs.examples.interfaces.Payment;

public class CardPayment implements Payment {

 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Card Payment done for Rs. " + amount);
  return true;
 }
 
 public void printSlip(){
  System.out.println("Printing slip for payment" );
 }
}

Note that in CardPayment class there is an extra method printSlip().

You do want to follow proper object oriented programming so you refer the instances of child classes CardPayment and CashPayment through the super type instance Payment. Only to call printSlip() method you will need downcasting to the child class.

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  //downcasting
  CardPayment cardPay = (CardPayment)pd;
  cardPay.printSlip();
 }
}

Running this will throw ClassCastException at run time-

Cash payment done for Rs. 100.0
Exception in thread "main" java.lang.ClassCastException: org.netjs.examples.impl.CashPayment cannot be cast to org.netjs.examples.impl.CardPayment
 at org.netjs.examples.impl.PaymentDemo.doPayment(PaymentDemo.java:17)
 at org.netjs.examples.impl.PaymentDemo.main(PaymentDemo.java:10)

When instance of CardPayment is passed to Payment reference there is no problem in downcasting it. There is a problem when instance of CashPayment is passed, widening the reference to Payment is ok but attempting to cast it to CardPayment is not possible as there is no parent-child relationship between these two classes. Both of them are child classes of Payment and instances of both of these classes are of type Payment but not interchangeable with each other.

Resolving ClassCastException in Java

To ensure that ClassCastException is not thrown you should check for the type of instance using instanceof operator in Java.

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  if (pd instanceof CardPayment){
   CardPayment cardPay = (CardPayment)pd;
   cardPay.printSlip();
  }
 }
}

Output

Cash payment done for Rs. 100.0
Card Payment done for Rs. 300.0
Printing slip for payment

Here note how instanceof operator is used to check the type and casting is done only if correct instance type is found thus avoiding ClassCastException.

That's all for this topic java.lang.ClassCastException - Resolving ClassCastException in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java
  2. Exception Propagation in Java Exception Handling
  3. finally Block in Java Exception Handling
  4. final Vs finally Vs finalize in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. matches() method in Java String
  2. Inheritance in Java
  3. AutoBoxing And UnBoxing in Java
  4. Reflection in Java - Getting Constructor Information
  5. Enum Type in Java
  6. Matrix Addition Java Program
  7. Spring NamedParameterJdbcTemplate Select Query Example
  8. Magic Methods in Python With Examples

Monday, June 27, 2022

Java Exception Handling And Method Overriding

OOPS concepts like inheritance are an integral part of Java as it is an obejct oriented language. When a class extends a super class it can also override methods of the super class.

But what about the exceptions thrown by a super class method? Should the overridden method in the child class also need to throw the same exceptions or it can change it. To address these scenarios there are some rules laid out. In this post Exception Handling and Method Overriding in Java we'll talk about those restrictions.

Broadly there are two rules for exception handling with method overriding in Java-

  • If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception with the throws clause.
  • If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
    1. sub-class can declare the same exception as declared in the super-class method.
    2. subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    3. subclass method can choose not to declare any exception at all.

Examples of Exception handling and method overriding in Java

Let's see examples of the scenarios listed above to make it clear.

If superclass method has not declared any exception

If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.

Java Exception handing and method overriding

It can be noted here that parent class' displayMsg() method deosn't have any throws clause whereas overridden method in the subclass declares IOException in its throws clause which is a checked exception. That's why the compile time error.

If we change the throws clause in subclass method to any unchecked exception then it won't result in compiler error.

public void displayMsg() throws ArrayIndexOutOfBoundsException{
}

If superclass method has declared an exception

  1. If superclass method has declared an exception then sub class can declare the same exception as declared in the superclass method.
    class Parent{
      public void displayMsg() throws IOException{
        System.out.println("In Parent displayMsg()");
      }
    }
    public class ExceptionOverrideDemo extends Parent{
      public void displayMsg() throws IOException{  
        System.out.println("In ExceptionOverrideDemo displayMsg()"); 
      }  
    }  
    
  2. subclass can declare the subtype exception of the exception declared in the superclass method.
    class Parent{
     public void displayMsg() throws IOException{
      System.out.println("In Parent displayMsg()");
     }
    }
    public class ExceptionOverrideDemo extends Parent{
     public void displayMsg() throws FileNotFoundException{  
      System.out.println("In ExceptionOverrideDemo displayMsg()"); 
     }  
    }
    

    Here in super class displayMsg() method throws IOException where as in subclass overridden displayMsg() method throws FileNotFoundException. Since FileNotFoundException is the subtype (Child class) of IOException so no problem here.

  3. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    Exception & method overriding in Java
    Here parent class method is throwing IOException whereas in the subclass overridden method is throwing Exception, it will result in compiler error as IOException is the child class of Exception class, thus Exception is up in the hierarchy.
  4. Subclass overridden method declares no exception. Subclass overridden method can choose to not throw any exception at all even if super class method throws an exception.
    class Parent{
      public void displayMsg() throws IOException{
        System.out.println("In Parent displayMsg()");
      }
    }
    public class ExceptionOverrideDemo extends Parent{
      public void displayMsg(){  
        System.out.println("In ExceptionOverrideDemo displayMsg()"); 
      }  
    }
    

That's all for this topic Java Exception Handling And Method Overriding. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Method Overriding in Java
  2. throw Statement in Java Exception Handling
  3. Multi-Catch Statement in Java Exception Handling
  4. Exception Propagation in Java Exception Handling
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Difference Between Abstract Class And Interface in Java
  2. strictfp in Java
  3. Marker Interface in Java
  4. ConcurrentHashMap in Java With Examples
  5. How HashMap Works Internally in Java
  6. Fail-Fast Vs Fail-Safe Iterator in Java
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class

Wednesday, May 25, 2022

finally Block in Java Exception Handling

In the post try-catch Block in Java we have already seen how to use try catch block for exception handling. In this post we'll get to know about finally block in Java which is used along with try catch block.

finally block in Java

When an exception occurs in the code, the flow of the execution may change or even end abruptly. That may cause problem if some resources were opened in the method where exception occurred.

For example, In a method a file was opened, while executing code in the method some exception occurred so the opened file was never closed, which effectively means that the resources will remain open consuming memory. Let's try to understand it with the following code.

1   public static void main(String[] args) {
2     BufferedReader br = null;
3     try{
4      String strLine;
5      // Instance of FileReader wrapped in a BufferedReader
6      br = new BufferedReader(new java.io.FileReader("F:\\abc.txt"));
7      ...
8      ...
9      ... //Exception happens here
10     ...
11     br.close()
12    }catch(IOException ioExp){
13     System.out.println("Error while reading file " + ioExp.getMessage());
14    }
15  }

At line 6 a BufferedReader stream is opened, which is closed in line 11. Suppose exception occurs at line 9 which changes the flow of the code execution because now the execution moves to catch block directly. Because of the exception, code execution moves from line 9 directly to line 13, meaning line 11 where stream is closed never getting executed.

You do need some mechanism to handle such scenarios. That's where finally block in Java helps by providing exception-handling mechanism to clean up.

Code with in the finally block will be executed after try/catch block has completed. Also note that the finally block in Java is always executed whether or not an exception is thrown.

If the code with in try block executes without throwing any exception, the finally block is executed immediately after the completion of try block. If an exception is thrown with in the try block, the finally block is executed immediately after executing the catch block (if exists) which handled the thrown exception.

Example of finally in Java

Note that, even if there is a return statement in try block, finally will be executed.

public class FinallyDemo {

 public static void main(String[] args) {
  int i = displayValue();
  System.out.println("Value of i " + i);
 }
 
 static int displayValue(){
  try{
   System.out.println("In try block");
   return 1;
  }finally{
   System.out.println("In finally block");
   return 2;
  }
 }
}

Output

In try block
In finally block
Value of i 2

It can be seen, though try block has a return value and no exception is thrown, still finally is executed. Ultimately return value is what finally returns.

Even if the exception is thrown still return value will be what finally returns. Let's see the same example again, this time an exception will be thrown.

public class FinallyDemo {

 public static void main(String[] args) {
  int i = displayValue();
  System.out.println("Value of i " + i);
 }
 
 static int displayValue(){
  try{
   System.out.println("In try block");
   throw new NullPointerException();
  }catch(NullPointerException nExp){
   System.out.println("Exception caught in catch block of displayValue");
   return 2;
  }finally{
   System.out.println("In finally block");
   //return 3;
  }
 }
}

Output

In try block
Exception caught in catch block of displayValue
In finally block
Value of i 3

Please note that it is not a good idea to return any thing from finally as it will suppress the exception. finally must be used for cleaning up.

Finally block Java example for cleaning up

A very good scenario when you should use finally block is when you are reading a file in Java. It is always advisable to close input and output streams in finally block in such cases to avoid resource kept opened in case of any exception.

public class FileRead {

 public static void main(String[] args) {
  BufferedReader br = null;
  try{
   String strLine;
   // Instance of FileReader wrapped in a BufferedReader
   br = new BufferedReader(new java.io.FileReader("F:\\abc.txt"));
   ...
   ...
  }catch(IOException ioExp){
   System.out.println("Error while reading file " + ioExp.getMessage());
  }finally {
   try {
    // Close the stream
    if(br != null){
     br.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

Points to note-

  • Every try block must be followed by at least one catch or a finally clause. So we can have any of these combinations try-catch, try-finally or try-catch-finally blocks.
  • When method is about to return from its try-catch block after normal execution flow or because of an uncaught exception, finally block is executed just before the method returns.
  • If there are multiple catch blocks and none of them can handle the exception thrown, even then the finally bock is executed.
  • Though there can be multiple catch blocks associated with a single try statement but there can only be single finally block associated with a try block. In case of nested try blocks there can be associated finally blocks with respective try blocks.
  • Finally block in Java is used to close the allocated resources (like file handles, database connections) before returning from the method.
  • It's not a good idea to return any value from finally as it may cause any exceptions that are not caught in the method to be lost.
  • If the JVM exits (through System.exit() or JVM crash) while the try or catch code is being executed, then the finally block may not execute. In case of multithreading if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

That's all for this topic finally Block in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. final Vs finally Vs finalize in Java
  2. Creating Custom Exception Class in Java
  3. throws Keyword in Java Exception Handling
  4. Exception Handling in Java Lambda Expressions
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. What Are JVM, JRE And JDK in Java
  2. Java Automatic Numeric Type Promotion
  3. Interface Static Methods in Java
  4. Creating a Thread in Java
  5. Synchronization in Java - Synchronized Method And Block
  6. How to Read Input From Console in Java
  7. How to Create PDF From XML Using Apache FOP
  8. Lambda Expression Examples in Java