Reputation: 87
i have a weird question. i had a quiz in my class today. One portion of the quiz was to find and correct errors in a short piece of code. one of the questions was like this
class Example {
public static void main(String[] args) {
try {
System.out.println("xyz");
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("abc");
}
}
}
I thought there was no error in the program but my professor insisted that there was. Can anyone guess what the error is?
Upvotes: 0
Views: 6532
Reputation: 72844
The "error" may be that you don't need to handle any exception here: System.out.println
does not specify any checked exception. It could simply be:
public static void main(String[] args) {
System.out.println("xyz");
}
Since the Exception
class covers both checked and unchecked exceptions, then if you add a catch
block here, in this case you would be handling only unchecked exceptions, which you should not normally handle.
Upvotes: 5
Reputation: 2009
The following code snippet would throw a compilation error if used with IOException
, since System.out.println
would never throw an IOException
but could throw Exception
or Throwable
which is its super class.
try {
System.out.println("xyz");
} catch (IOException e) {
//simple display error statement here
} finally {
//simple print statement here
}
Upvotes: 0
Reputation: 3306
There is no Error in the Above Program , but also there is no need to put a try{} catch{}
....since you don't use any code that can throw an Exception , for example a risky method like Thread.sleep();
So maybe that’s what your professor meant .
Upvotes: 1
Reputation: 7743
Well, I see nothing that would keep this from compiling, but I do see some problems. To begin with, there are comments indicating the presence of code which is not there. Comments out of sync with code is always a problem. [EDIT: indentation errors have been edited away] And you're catching Exception e, which you really oughtn't to do. You should always catch a specific exception that you expect to encounter, and handle it specifically. Since there's no exception that System.out.println can throw, this would make the whole Exception handling block a problem.
Upvotes: 0