0

I was reading the Exception Handling in Java and was facing problem to understand the below exception method.

public static Object deserialize() throws IOException,
        ClassNotFoundException {}

another

try {
    } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }

I Know how try and catch works. But I don't know how throws IOException,ClassNotFoundException in my First example.

What is the Difference? and which should I choose?

I know it could be stupid question, because I don't know how I can search on Google for this.

  • @Downvoter Please read my Last line. :( –  Sep 18 '15 at 16:52
  • 2
    http://stackoverflow.com/questions/3203297/throws-or-trycatch – Bohuslav Burghardt Sep 18 '15 at 16:52
  • The first says that it is best for the caller to know that an exception has occurred, and should handle it as they see fit. The second says that the coder used an ide to generate a try-catch block and couldn't be bothered/didn't know how to write something more appropriate. – Andy Turner Sep 18 '15 at 16:59
  • 2
    So because you _know it's a stupid question_, we shouldn't downvote it? I don't think you understand how Stack Overflow works. The downvote button is there for specific reasons. You can get them by hovering over it. – Sotirios Delimanolis Sep 18 '15 at 17:01
  • @SotiriosDelimanolis Ok No Problem.. I will accept just to learn.. Thanks. –  Sep 18 '15 at 17:24

1 Answers1

0

The second example handles the exceptions in your method itself. And the first example puts this resposibility on to the the caller of your method. So they can handle/ throw these exceptions.

If you know what to do when these excewptions occur then use second-way. If you don't know what to do and want the caller to take action on these exceptions then use first-way.

Balkrishna Rawool
  • 1,865
  • 3
  • 21
  • 35
  • can you explore your about `And the first example puts this resposibility on to the the caller of your method.` –  Sep 18 '15 at 17:45
  • 1
    By 'this responsibility' I meant 'handling the exceptions'. In first example, the method declares that it can throw these exceptions. So the caller of this method should take note of this and then should decide whether to handle these exceptions or re-throw them. – Balkrishna Rawool Sep 18 '15 at 18:25