0

finally block would execute if an exception is thrown in try block here:

public class ExceptionTest{
public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static int  print()
 {
  try
  {
   throw new NullPointerException();
   
  }
  finally
  {
   System.out.println("Executing finally block"); 
   
  }
 }
 }

output:

Executing finally block
Exception in thread "main" java.lang.NullPointerException
    at ExceptionTest.print(ExceptionTest.java:11)
    at ExceptionTest.main(ExceptionTest.java:4)

In the other hand finally won't be called in this code right here:

public class ExceptionTest{
public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static int  print()
 {
  try
  {
   throw new Exception();
   
  }
  finally
  {
   System.out.println("Executing finally block"); 
   
  }
 }
 }

output:

ExceptionTest.java:11: error: unreported exception Exception; must be caught or declared to be thrown
   throw new Exception();
   ^
1 error

why it is cool with NullPointerException class but it complains when it comes to Exception class?

luk2302
  • 55,258
  • 23
  • 97
  • 137
Amani
  • 11
  • 1
  • `NullPointerException` is an **unchecked exception**. – luk2302 Jul 08 '20 at 17:26
  • Right the finally block won't run if the entire program won't run – Joni Jul 08 '20 at 17:29
  • @luk2302 when I started study about finally block I read " The finally block always executes when the try block exits. So you can use finally without catch but you must use try." https://stackoverflow.com/questions/17314724/is-it-valid-to-have-finally-block-without-try-and-catchI thought this's possibe for all kinds of exception. – Amani Jul 08 '20 at 18:45
  • Your code does not run at all, it does not even *compile*. The statement about `finally` remains true but simply does not apply to your situation since there is nothing running in the first place. – luk2302 Jul 08 '20 at 18:46
  • @luk2302 thank you a looot I got it now . – Amani Jul 08 '20 at 18:53

1 Answers1

0

NullPointerException is an unchecked exception. Check this guide.

Here is an example of a try and catch block which catches everything:

try {
    //Do Something
    }
 
catch (Exception e) {
      System.out.println("Something went wrong.");
    } 

finally {
      System.out.println("The 'try catch' is finished.");
    }
AztecCodes
  • 1,130
  • 7
  • 23