0
public static String doSomething()  {
    String name = "ABC";
    try {
        throw new IOException();
    } finally {
       return name;
    }
} 

O/p:ABC

However below code needs throws in the method signature. Is it because return statement is missing or any other reason?

 public static String doSomething() throws IOException {
    String name = "ABC";
    try {
        throw new IOException();
    } finally {
       System.out.println("hello");
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
learningIsFun
  • 142
  • 1
  • 9

1 Answers1

3

Your first method can't throw an IOException. The return statement in the finally block effectively swallows any exception that would have been thrown (i.e. the IOException that you explicitly throw in the try block).

Your second method absolutely will throw an IOException, and because that's a checked exception, you need a throws clause to tell the caller that.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194