Scruffy
Scruffy

Reputation: 580

Java: Automatic 'throws' declaration: is it, and if so, what is its value?

Take any method for example. public static void main(String[] args) is as good as any other. If I have code therewithin that will throw, for example, a NullPointerException, why don't I have to declare that my method throws this?

Is assumption that without definition, all methods will throw some specific predefined exceptions, correct? If so, what are they?

To clarify, I am not seeking help with broken code, but asking a question about how Java itself works.

Upvotes: 0

Views: 211

Answers (3)

Anderson Vieira
Anderson Vieira

Reputation: 9059

Java has checked and unchecked exceptions. From the documentation:

The unchecked exception classes are the run-time exception classes and the error classes.

The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.

NullPointerException is an example of an unchecked exception. This means that you are not forced to catch it or add the throws NullPointerException for every method that has a chance of throwing it.

FileNotFoundException is a checked exception. So if you use a FileInputStream, which throws a FileNotFoundException, you need to either surround it with a try-catch block or declare that the method it is in throws a FileNotFoundException.

Upvotes: 1

Kartic
Kartic

Reputation: 2983

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

Upvotes: 1

ch271828n
ch271828n

Reputation: 17643

There are two main sets of Exception. One is the ones who inherits RuntimeException. You need not define it (as void f() throws SomeException). These are called unchecked exception.

For the other ones you have to. They are called checked exception.

For more details, see here

Upvotes: 1

Related Questions