Java provides two main types of exceptions: Runtime exception and checked exception. All the checked exception are derived from the Java.lang.Exception class, and runtime Exception are derived from Java.lang.RuntimeException or Java.lang.Error classes.
Their differences are manifested in two aspects: the mechanism and the logic.
First, the mechanism
Their differences in mechanism are expressed at two points: 1. How to define methods; 2. How to handle the thrown exception. Consider the following checkedexception definition:
public class CheckedException extends Exception
{
public CheckedException() {}
public CheckedException( String message )
{
super( message );
}
}
And an example of using exception:
public class ExceptionalClass
{
public void method1()
throws CheckedException
{
// ... throw new CheckedException( “...出错了“ );
}
public void method2( String arg )
{
if( arg == null )
{
throw new NullPointerException( “method2的参数arg是null!” );
}
}
public void method3() throws CheckedException
{
method1();
}
}
As you may have noticed, two methods method1 () and METHOD2 () will throw the exception, but only method1 () make a declaration. In addition, METHOD3 () itself does not throw exception, but it declares that it throws checkedexception. Before explaining to you, let's take a look at the main () method of this class:
public static void main( String[] args )
{
ExceptionalClass example = new ExceptionalClass();
try
{
example.method1();
example.method3();
}
catch( CheckedException ex ) { } example.method2( null );
}
In the main () method, if you want to invoke Method1 (), you must place the call in the Try/catch block because it throws checked exception.
In contrast, when you call METHOD2 (), you do not need to place it in the Try/catch block, because it throws exception not checked exception, but runtime exception. A method that throws runtime exception does not have to declare that it throws a exception when it is defined.
Now, let's take a look at method3 (). It calls Method1 () but does not place the call in the Try/catch program block. It is avoided by declaring that it throws the exception that Method1 () throws. It does not capture this exception, but it passes it down. In fact, the main () method can also do this by declaring that it throws checked exception to avoid using the Try/catch program block (which we are opposed to).