Here's my code:
class FinallyDemo {
static void myMethod(int n) throws Exception{
try {
switch(n) {
case 1:
System.out.println("1st case");
return;
case 3:
System.out.println("3rd case");
throw new RuntimeException("3!");
case 4:
System.out.println("4th case");
throw new Exception("4!");
case 2:
System.out.println("2nd case");
}
catch (RuntimeException e) {
System.out.print("RuntimeException: ");
System.out.println(e.getMessage());
} finally {
System.out.println("try-block entered.");
}
}
public static void main(String args[]){
for (int i=1; i<=4; i++) {
try {
FinallyDemo.myMethod(i);
} catch (Exception e){
System.out.print("Exception caught: ");
System.out.println(e.getMessage());
}
System.out.println();
}
}
}
Now, doesnt it work this way:
If I have a try and catch block in the method itself then I need not write
method_name(int n) throws Exception
?
Doesnt try-catch block in the method that throws exception prevents from writing "throws exception" in the method that throws exception?
In your example, the case 4 throws an exception while in the catch you are just catching the RuntimeException. Since there is not catch for Exception, your method needs to declare that it throws Exception. If you were to add a catch for Exception, you wouldn't need to throw Exception. This will work.
static void myMethod(int n) {
try {
switch (n) {
case 1:
System.out.println("1st case");
return;
case 3:
System.out.println("3rd case");
throw new RuntimeException("3!");
case 4:
System.out.println("4th case");
throw new Exception("4!");
case 2:
System.out.println("2nd case");
}
} catch (RuntimeException e) {
System.out.print("RuntimeException: ");
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(e.getMessage());
}
finally {
System.out.println("try-block entered.");
}
}