0

I have these two java codes:

class test {
    public static void main(String[] args) throws IOException {
        System.out.println("Before try”");
        try{}
        catch(Throwable d ) {}
        System.out.println("done");
    }
}

it will compile and print Before try and done.

class test {
    public static void main(String[] args) throws IOException {
        System.out.println("Before try”");
        try{}
        catch(java.io.IOException e ) {}
            System.out.println("done");
        }
    }
}

this will make compilation error:

exception java.io.IOException is never thrown in body of corresponding 
try statement
    at javaapplication8.test.main(Try.java:63) 

what is the difference between throwable exception and IOException to have these results, Is there a rule to know which exception would need to be thrown or not?

Barranka
  • 20,547
  • 13
  • 65
  • 83
user3159060
  • 131
  • 1
  • 1
  • 8
  • Catching `Throwable` is bad practice because it will catch not only `Exceptions` but also `Errors` – baju Jan 27 '15 at 21:15
  • 1
    Catching `Throwable` is good practice if you are at the outer most scope of a task or thread i.e. only as a last measure, but otherwise you should avoid it. – Peter Lawrey Jan 27 '15 at 21:17
  • @PeterLawrey Yup, probably it is just single case in which it makes sense but good practice in my opinion is strong phrase – baju Jan 27 '15 at 21:26
  • @baju it's rarely needed in most code, but submit() to an ExecutorService without keeping the Future and you have Exceptions disappearing unless you have a catch all. – Peter Lawrey Jan 27 '15 at 21:28
  • @PeterLawrey Definitely there are cases in which it is good idea (otherwise language will do not offer such possibility) but I think every example should be analyzed carefully as it could lead to the serious problems. [click](http://stackoverflow.com/questions/6083248/is-it-a-bad-practice-to-catch-the-throwable) – baju Jan 27 '15 at 21:33
  • @baju BalusC is very explicit on his answer: you need to be as specific as possible. And you don't want to catch `Error` :) – Luiggi Mendoza Jan 27 '15 at 21:35
  • @LuiggiMendoza catching Error and logging it is better than dying silently. – Peter Lawrey Jan 27 '15 at 22:03

2 Answers2

1

Java has a concept of checked exceptions. All Throwable are checked unless they are a sub-class of Error or RuntimeException

In the catch class, the compiler can work out whether you can throw a checked exception or not (under normal conditions), but it can't tell if you have thrown an unchecked exception so if you catch any unchecked exception, or an parent, it cannot determine whether you might throw it or not.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Your declaration of main promised that it could throw an IOException, but your code broke that promise (because you catch it yourself).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101