Search code examples
javaexception

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?


Solution

  • 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.