Coming from C#, I just don\'t get this \'throws exception\' that is written after a class/method definition:
public void Test() throws Exception
You don't have to write it in all cases -- you just have to write it if your method throws a checked Exception
(an exception that is a subclass of Exception
and not a subclass of RuntimeException
). This is because your method signature is a contract, and it's declaring to all the code which calls it that it has the potential for throwing the given exception. Because it's a checked exception -- an exception which can be anticipated -- the calling code needs to anticipate the potential of seeing the exception thrown, and needs to be able to handle it.
To answer your two specific questions:
bar
can throw SomeException
, and method foo
calls bar
and doesn't want to catch the exception, the method signature for foo
would declare that it too throws SomeException
.The Exceptions chapter of the Java lessons is very good at explaining this in detail, and JavaWorld has a good article about throwing and catching exceptions that I've always found to be a good reference to pass onto folks.
"throws" keyword is used if the exception may not gonna handle in current method and it can be propagated to the caller of that method.
The caller can either handle that exception or propagate that exception to another method by using "throws" keyword.
The Exception class is base class for Runtime Exception.
You don't have to throw the exception if you catch the exception in your code. If you don't catch it, it gets passed along to the caller, which is why you would need the throws clause.