I came from .net world.
I have some question about exceptions in java.
What is deference between two attitude of throwing exceptions:
public void f() throws Exception {
//some logic
}
and this:
public void f() {
//some logic
throw new Exception();
}
When should I use first attitude and the second attitude?
In Java, you need to specify how your method behaves. This includes exceptions that can possibly be thrown. To declare, that you method can that an exception, the throws
keyword is used (as in your first Example).
Note that only Exceptions that derive from the Exception
class must be depicted here (there are also RuntimeExceptions
and other Throwables
that do not need to be depicted. More here).
To throw an Exception you need the keyword throw
followed by the instance of any Exception
(to be precise, you can throw any Throwable
).
A valid method would be:
public void foo() throws Exception {
throw new Exception();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments