简体   繁体   中英

Java : Unknown error in exception handling

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?

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.

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 .

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM