Search code examples
javaexceptionawtchecked-exceptions

Program complies even when we do not handle the checked Exception thrown by Frame constructor?


As per Oracle Documentation https://docs.oracle.com/javase/7/docs/api/java/awt/Frame.html#Frame()

Frame constructor throws HeadlessException - when GraphicsEnvironment.isHeadless() returns true

But the program runs without handling the Exception when the constructor is called

import java.awt.*;
import java.awt.event.*;
public class MouseDemo extends Frame{
    String msg="";

    MouseDemo()
    {
        super();//not handling HeadlessException
        addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent me)
            {
                msg="Clicked";
                repaint();

            }

        });

        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        } );
    }
    @Override
    public void paint(Graphics g)
    {
        g.setColor(Color.black);
        g.drawString(msg, 50, 50);
    }
    public static void main(String agrs[])
    {
        MouseDemo obj=new MouseDemo();
        obj.setSize(new Dimension(300,300));
        obj.setTitle("hello");
        obj.setVisible(true);
    }

    
}

MouseDemo() neither handle the HeadlessException nor throws it to the calling method then why are we not getting compilation error


Solution

  • As §8.4.6 of the Java Language Specification puts it,

    It is permitted but not required to mention unchecked exception classes (§11.1.1) in a throws clause.

    So not everything you see in a throws clause is a checked exception. In fact, checked exceptions are defined in §11.1.1:

    RuntimeException and all its subclasses are, collectively, the run-time exception classes.

    The unchecked exception classes are the run-time exception classes and the error classes.

    The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are Throwable and all its subclasses other than RuntimeException and its subclasses and Error and its subclasses.

    If you look at HeadlessException's inheritance tree, you will see that it is a subclass of RuntimeException:

    java.lang.Object
      java.lang.Throwable
        java.lang.Exception
          java.lang.RuntimeException
            java.lang.UnsupportedOperationException
              java.awt.HeadlessException
    

    Therefore, it is an unchecked exception, and you are not required to handle it with either a try...catch or another throws clause.