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
As §8.4.6 of the Java Language Specification puts it,
So not everything you see in a
throwsclause is a checked exception. In fact, checked exceptions are defined in §11.1.1:If you look at
HeadlessException's inheritance tree, you will see that it is a subclass ofRuntimeException:Therefore, it is an unchecked exception, and you are not required to handle it with either a
try...catchor anotherthrowsclause.