I have the following code. In that fn2 is actually throwing an exception and it is caught in the function itself. In the function fn1 the compiler is complaining about unhandled exception since fn2 is declared to be throwing an Exception.
Why it is so? Since the exception is caught inside fn2 it shouldn't be complaining right?
Please explain the behavior.
public class ExepTest {
/**
* #param args
*/
public static void main(String[] args) {
ExepTest exT = new ExepTest();
exT.fn1();
}
public void fn1(){
fn2();//compilation error
}
public void fn2() throws Exception{
try{
throw new Exception();
}
catch(Exception ex){
System.out.println("Exception caught");
}
}
}
Compiler doesn't/can't know that at runtime no exception will be throwed by fn2() since it's declared that it may throw an Exception, that's why you got an error.
Remove the throws Exception from fn2() signature
The signature of the method fn2 is all that matters here. In that signature you declare that fn2 may throw an Exception. Any code that calls a method that may throw an Exception must handle the eexception.
public void fn2() throws Exception. The compiler see that declaration and expect each caller to fn2 to handle / rethrow the exception.
Exception is thrown BY fn2, not inside it. So it will be actually thrown where it is called. Since it is called in fn1, it is behaving like this.
You need to surround the call to fn2() in a try-catch block, or declare that fn1 also throws an exception.
public void fn1(){
fn2();//compilation error
}
public void fn2() throws Exception{
try{
throw new Exception();
}
catch(Exception ex){
System.out.println("Exception caught");
}
}
}
Here compiler will not recognize that you have handled exception or not. It just assumes that fn2 throws exception as you have declared to be and that's why it's showing error.
To run program either remove throws Exception from fn2 or write throws Exception in fn1 or handle it in try..catch in fn1.
Related
So I thought I had a good basic understanding of exception-handling in Java, but I was recently reading some code that gave me some confusion and doubts. My main doubt that I want to address here is when should a person use throws in a Java method declaration like the following:
public void method() throws SomeException
{
// method body here
}
From reading some similar posts I gather that throws is used as a sort of declaration that SomeException could be thrown during the execution of the method.
My confusion comes from some code that looked like this:
public void method() throws IOException
{
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
Is there any reason that you would want to use a throws in this example? It seems that if you are just doing basic exception-handling of something like an IOException that you would simply need the try/catch block and that's it.
If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.
Typically, if you are not going to do anything with the exception, you should not catch it.
The most dangerous thing you can do is catch an exception and not do anything with it.
A good discussion of when it is appropriate to throw exceptions is here
When to throw an exception?
You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws is
unnecesary.
Remove the try/catch; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly
perform some action and then rethrow
the exception (not just the message)
You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.
Something like:
public void method() throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
or
public void method() {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println("Catching IOException");
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
System.out.println(e.getMessage());
}
}
In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.
This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.
Lets say there is
public static void main(String[] args) {
try {
// do nothing or throw a RuntimeException
throw new RuntimeException("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
The output is
test
Exception in thread "main" java.lang.RuntimeException: test
at MyClass.main(MyClass.java:10)
That method does not declare any "throws" Exceptions, but throws them!
The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method.
It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception
Now, if we have
public static void main(String[] args) throws Exception {
try {
throw new Exception("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.
Can anyone please give me information about it. I cant really uderstand the type of this Exception.
Thank you
public class ValidationException extends Exception{
public ValidationException(){
super("There was a problem when validating data");
}
public ValidationException(String message){
super(message);
}
public ValidationException(String message, Throwable throwable){
super(message, throwable);
}
public ValidationException(Throwable throwable){
super(throwable);
}
}
It is a "runtime exception" in the (fatuous) sense that it is an exception that occurs at runtime. But that is true for all Java exceptions ... apart from bugs in the compiler, etcetera.
It is not a subclass of RuntimeException. You have declared it as a subclass of Exception and Exception is not a subclass of RuntimeException. (In fact, the reverse is true: RuntimeException is a subclass of Exception!)
It is a checked exception because it is not a subclass of RuntimeException (or Error).
Since it is a checked exception, the Java rules about checked exceptions apply. For example, any method that throws or propagates1 your exception must declare that it throws this exception, or an exception that is a superclass of this exception.
1 - Technically, the JLS describes this as an abnormal termination of the method body with this exception as the abnormal termination reason.
The main difference between Exception, and RuntimeException is that we need to wrap a Exception in a try/catch block. A RuntimeException does not need to be caught, but it is just as lethal as an Exception.
public class Main{
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler(){
#Override
public void uncaughtException(Thread t, Throwable e){
System.out.println("Uncaught Exception " + e);
}
});
try{
throwException();
}catch(Exception e){
System.out.println("Caught Exception " + e);
}
try{
throwRuntimeException();
}catch(Exception e){
System.out.println("Caught RuntimeException " + e);
}
//unchecked, no need to wrap int try/catch
throwRuntimeException();
}
public static void throwException() throws Exception {
throw new Exception();
}
public static void throwRuntimeException() {
throw new RuntimeException();
}
}
Take this example above. The output is this:
Caught Exception java.lang.Exception
Caught RuntimeException java.lang.RuntimeException
Uncaught Exception java.lang.RuntimeException
As you can tell, the call to throwRuntimeException() gets thrown, and since there is no try/catch block it has no idea how to handle it. This crashes the thread and since there is an UncaughtExceptionHandler it gets called.
Then there is also Error which I won't go into since I don't know much about it besides that JVM throws it. OutOfMemoryError is an example.
I have these two java codes:
class test {
public static void main(String[] args) throws IOException {
System.out.println("Before try”");
try{}
catch(Throwable d ) {}
System.out.println("done");
}
}
it will compile and print Before try and done.
class test {
public static void main(String[] args) throws IOException {
System.out.println("Before try”");
try{}
catch(java.io.IOException e ) {}
System.out.println("done");
}
}
}
this will make compilation error:
exception java.io.IOException is never thrown in body of corresponding
try statement
at javaapplication8.test.main(Try.java:63)
what is the difference between throwable exception and IOException to have these results, Is there a rule to know which exception would need to be thrown or not?
Java has a concept of checked exceptions. All Throwable are checked unless they are a sub-class of Error or RuntimeException
In the catch class, the compiler can work out whether you can throw a checked exception or not (under normal conditions), but it can't tell if you have thrown an unchecked exception so if you catch any unchecked exception, or an parent, it cannot determine whether you might throw it or not.
Your declaration of main promised that it could throw an IOException, but your code broke that promise (because you catch it yourself).
I get this error when compiling my program:
./GUI/mainWindow.java:30: error: unreported exception Exception; must be caught or declared to be thrown
clientUI.initClientUI();
^
1 error
But my method actually throws Exception:
public final void initClientUI() throws Exception {
However, if I remove the "throws Exception" part, try to compile, then add it again, the program compiles successfully. Can anyone explain why is this happening?
EDIT:
If I add "throws Exception" to the method I am calling
public void actionPerformed(ActionEvent e) throws Exception { //<-----add Exception there
ClientWindow clientUI = new ClientWindow();
clientUI.initClientUI();
I get this error:
./GUI/mainWindow.java:28: error: actionPerformed(ActionEvent) in <anonymous GUI.mainWindow$1> cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed(ActionEvent e) throws Exception {
^
overridden method does not throw Exception
1 error
By saying
public final void initClientUI() throws Exception {
you are telling the compiler that initClientUI() is allowed to throw Exception or any subclass of Exception. Since Exception is checked, any method that calls initClientUI() must either catch Exception or have it listed in its throws clause.
I'd recommend reading the tutorial on exceptions.
Your problem is not the declaration of your method, your problem is when you call it. When you declare a method like this
public final void initClientUI() throws Exception
your compiler will know that it will throw an exception. That's good, no problem so far. But when you call it, you have to deal with this exception.
So when you say
client.initClientUI()
your compiler says "this method throws an exception, pleas handle it". Now you have two options:
try {
client.initClientUI()
}
catch(Exception e) {
System.out.println(e);
}
or declare your method that calls client.initClientUI() also with throws Exception.
throws Exception means you are throwing it to the calling method,And Calling method should be responsible of handeling that exception either by throwing it again or catching it with try catch.
You should do it this way
public void actionPerformed(ActionEvent e) {
try{
ClientWindow clientUI = new ClientWindow();
clientUI.initClientUI();
}catch(Exception e){
// handle exception
}
Can any of you explain what the differences are between throw, throws and Throwable and when to use which?
throws : Used when writing methods, to declare that the method in question throws the specified (checked) exception.
As opposed to checked exceptions, runtime exceptions (NullPointerExceptions etc) may be thrown without having the method declare throws NullPointerException.
throw: Instruction to actually throw the exception. (Or more specifically, the Throwable).
The throw keyword is followed by a reference to a Throwable (usually an exception).
Example:
Throwable: A class which you must extend in order to create your own, custom, throwable.
Example:
Official exception-tutorial
throw: statement to throw object t where t instanceof java.lang.Throwable must be true.
throws: a method signature token to specify checked exceptions thrown by that method.
java.lang.Throwable: the parent type of all objects that can be thrown (and caught).
See here for a tutorial on using exceptions.
This really easy to understand.
The java.lang.Throwable:
The Throwable class is
the superclass of all errors and
exceptions in the Java language. Only
objects that are instances of this
class (or one of its subclasses) are
thrown by the Java Virtual Machine or
can be thrown by the Java
throw statement.
Similarly, only this class or one of
its subclasses can be the argument
type in a catch clause.
More
The key word throws is used in method declaration, this specify what kind of exception[Throwable class] we may expect from this method.
The key word throw is used to throw an object that is instance of class Throwable.
Lest see some example:
We create ourself an exception class
public class MyException super Exception {
}
The we create a method that create a object from our exception class and throws it using key word throw.
private void throwMeAException() throws MyException //We inform that this method throws an exception of MyException class
{
Exception e = new MyException (); //We create an exception
if(true) {
throw e; //We throw an exception
}
}
When we are going to use method throwMeAException(), we are forced to take care of it in specific way because we have the information that it throws something, in this case we have three options.
First option is using block try and catch to handle the exception:
private void catchException() {
try {
throwMeAException();
}
catch(MyException e) {
// Here we can serve only those exception that are instance of MyException
}
}
Second option is to pass the exception
private void passException() throws MyException {
throwMeAException(); // we call the method but as we throws same exception we don't need try catch block.
}
Third options is to catch and re-throw the exception
private void catchException() throws Exception {
try {
throwMeAException();
}
catch(Exception e) {
throw e;
}
}
Resuming, when You need to stop some action you can throw the Exception that will go back till is not server by some try-catch block. Wherever You use method that throws an exception You should handle it by try-catch block or add the declarations to your methods.
The exception of this rule are java.lang.RuntimeException those don't have to be declared. This is another story as the aspect of exception usage.
throw - It is used to throw an Exception.The throw statement requires a single argument : a throwable class object
throws - This is used to specifies that the method can throw exception
Throwable - This is the superclass of all errors and exceptions in the Java language. you can throw only objects that derive from the Throwable class. throwable contains a snapshot of the execution stack of its thread at the time it was created
Throw is used for throwing exception, throws (if I guessed correctly) is used to indicate that method can throw particular exception, and the Throwable class is the superclass of all errors and exceptions in the Java
How to Throw Exceptions
Throw :
is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.
throw new MyException("Exception!);
Throws:
This is to be used when you are not using the try catch statement in your code but you know that this particular class is capable of throwing so and so exception(only checked exceptions). In this you do not use try catch block but write using the throw clause at appropriate point in your code and the exception is thrown to the caller of the method and is handled by it. Also the throws keyword is used when the function may throw a checked exception.
public void myMethod(int param) throws MyException
There are 2 main types of Exceptions:
Runtime Exceptions(unchecked): eg. NullPointerException, ClassCastException,.. Checked Exceptions: eg. FileNotFoundException, CloneNotSupportedException, ..
Runtime Exceptions are exceptions that occur at runtime and the developer should not try to catch it or stop it. You only write code to avoid them or issue a command throw, when the error criteria is met. We use throw inside the method body.
public Rational(int num, int denom){
if(denom <= 0) {
throw new IllegalArgumentException("Denominator must be positive");
}
this.num=num;
this.denom=denom;
}
However for Checked Exceptions, the JVM expects you to handle it and will give compiler error if not handled so you declare that it throws that type of exception as seen below in the clone() method.
Class Employee{
public Employee clone() throws CloneNotSupportedException{
Employee copy = (Employee)super.clone();
copy.hireDate = (Date)hireDate.clone();
return copy;
}
}
Same answer as above but with copy-paste pleasure:
public class GsonBuilderHelper {
// THROWS: method throws the specified (checked) exception
public static Object registerAndRun(String json) throws Exception {
// registering of the NaturalDeserializer
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
Object natural = null;
try {
// calling the NaturalDeserializer
natural = gson.fromJson(json, Object.class);
} catch (Exception e) {
// json formatting exception mainly
Log.d("GsonBuilderHelper", "registerAndRun(json) error: " + e.toString());
throw new Exception(e); // <---- THROW: instance of class Throwable.
}
return natural;
}
}