Reputation: 3064
I'm learning to use java, I think I already know the basics of C++. But, as I just started learning java, the first bits of 'hello world' program I noticed uses 'throws exception' when initiating the main function in the main class. Why is it used? Do we do something similar in c++? Is returning 0 in int type main function in c++ a similar thing?
Upvotes: 1
Views: 374
Reputation: 153909
It isn't, or at least, I've never seen a main
in Java which
did it. I'm not even sure that it's legal. (Given the way Java
uses exceptions, it shouldn't be. Only RuntimeException
and
Error
should propagate out of main
.)
Java tends to overuse exceptions; especially, it uses exceptions in cases where return values would be more appropriate (e.g. things like not being able to open a file). In a correct program, these exceptions must be handled (just as in a correct program, C++ returned error codes, or in the case of input and output, the stream state, must be handled). Java uses the exception specifier to declare these exceptions (and only these—it isn't necessary to declare things that would be an exception in C++).
Upvotes: 1
Reputation: 2611
In Java, specifying that a methodthrows SomeException
means that any method calling that method will have to either catch or itself throw that exception. In the case of the main function, it just means that you don't have to catch any exceptions that may occur directly in the main method, they will instead be passed on to the underlying runtime, resulting in a stack trace print and program exit.
Upvotes: 2