I have two versions of code. In the first version type of exception which is throwed in Method() – NullPointerException, in the second version – Exception. However first version will compile but second won’t compile. Why is this happen?
public class Demo
{
static void Method()
{
try
{
throw new NullPointerException("error");
}
catch(Exception ex)
{
throw ex;
}
}
public static void main(String argv[])
{
try
{
Method();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
This is the second version.
public class Demo
{
static void Method()
{
try
{
throw new Exception("error");
}
catch(Exception ex)
{
throw ex;
}
}
public static void main(String argv[])
{
try
{
Method();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
stack trace for first version:
java.lang.NullPointerException: error
at Demo.Method(Demo.java:7)
at Demo.main(Demo.java:18)
This is because
NullPointerExceptionis a so-called “unchecked” exception. You don’t need to declare them in thethrowsclause.However, a casual
Exceptionis not unchecked, and you do need to declare in athrowsdeclaration. You need to makeMethod()throwExceptionin your second code snippet.Unchecked exceptions are
RuntimeException,Errorand derivate classes.NullPointerExceptionderivates fromRuntimeException.