Two exceptions in Java

Source: Internet
Author: User

Java provides two main types of exceptions: runtime exception and checked exception. All checked exceptions are derived from the java. lang. exception class, while the runtime Exception is derived from the java. lang. RuntimeException or java. lang. Error class.

Their differences are manifested in two aspects: Mechanism and logic.
I. Mechanism

Their mechanisms differ in two aspects: 1. How to define methods; 2. How to handle thrown exceptions. See the following

CheckedException definition:

Java code
Public class CheckedException extends Exception {
Public CheckedException (){}
Public CheckedException (String message ){
Super (message );
}
}

Public class CheckedException extends Exception {
Public CheckedException (){}
Public CheckedException (String message ){
Super (message );
}
} And an example using exception:

Java code
Public class ExceptionalClass {

Public void method1 () throws CheckedException {
//...
Throw new CheckedException ("... error ");
}
Public void method2 (String arg ){
If (arg = null)
{
Throw new NullPointerException ("the parameter arg of method2 is null! ");
}
}
Public void method3 () throws CheckedException {
Method1 ();
}
}

Public class ExceptionalClass {

Public void method1 () throws CheckedException {
//...
Throw new CheckedException ("... error ");
}
Public void method2 (String arg ){
If (arg = null)
{
Throw new NullPointerException ("the parameter arg of method2 is null! ");
}
}
Public void method3 () throws CheckedException {
Method1 ();
}
} You may have noticed that both methods method1 () and method2 () throw an exception, but only method1 () is declared. In addition, method3 () itself does not throw an exception, but it declares that it will throw CheckedException. Before explaining it to you, let's take a look at the main () method of this class:

Java code
Public static void main (String [] args)
{

Predictionalclass example = new predictionalclass ();
Try
{
Example. method1 ();
Example. method3 ();
} Catch (CheckedException ex ){

}
Example. method2 (null );
}

Public static void main (String [] args)
{

Predictionalclass example = new predictionalclass ();
Try
{
Example. method1 ();
Example. method3 ();
} Catch (CheckedException ex ){

}
Example. method2 (null );
} In the main () method, if you want to call method1 (), you must put this call in the try/catch Block because it will throw a Checked exception.

In contrast, when you call method2 (), you do not need to place it in the try/catch Block, because the exception it throws is not a checked exception, but a runtime exception. A method that throws a runtime exception does not need to be declared during definition. It throws an exception.

Now, let's take a look at method3 (). It calls method1 () but does not place this call in the try/catch Block. It avoids this by declaring that it will throw the exception thrown by method1. Instead of capturing this exception, it passes it down. In fact, the main () method can also do this. Declaring it will throw a Checked exception to avoid using the try/catch Block (of course we are against this practice ).

Summary:

1. Runtime exceptions:

A runtime exception is thrown if no declaration is required during method definition;

You do not need to capture this runtime exception when calling this method;

Runtime exception is derived from the java. lang. RuntimeException or java. lang. Error class.

2. Checked exceptions:

When defining a method, you must declare all possible checked exceptions;

When calling this method, you must capture its checked exception; otherwise, you must pass its exception;

Checked exception is derived from the java. lang. Exception class.

Ii. Logic

Logically, checked exceptions and runtime exception have different purposes. Checked exception indicates an exception that can be directly handled by the caller. Runtime exception indicates a program error that the caller cannot handle or recover.

Checked exception forces you to capture it and handle this exception. Take the constructor of the java.net. URL class as an example. Every builder of the java.net. URL class throws MalformedURLException. MalformedURLException is a checked exception. Imagine that you have a simple program that prompts the user to enter a URL and then download a webpage through this URL. If the URL entered by the user is incorrect, the builder throws an exception. Since this exception is a checked exception, your program can capture it and handle it correctly: for example, you are prompted to re-enter it.

 

Let's look at the example below:

Java code
Public void method ()
{

Int [] numbers = {1, 2, 3 };
Int sum = numbers [0] + numbers [3];
}

Public void method ()
{

Int [] numbers = {1, 2, 3 };
Int sum = numbers [0] + numbers [3];
} When running method (), ArrayIndexOutOfBoundsException is encountered (because the members of the array numbers are from 0 to 2 ). The caller cannot handle or correct this exception. This method () is the same as the preceding method2 () method. It is a runtime exception. As mentioned above, runtime exception is used to indicate a program error that the caller cannot handle/recover. Generally, program errors cannot be processed during running. You must correct the program code.

All in all, when a checked exception is thrown during program running, only calls that can properly handle this exception should be captured using try/catch. For a runtime exception, it should not be captured in the program. If you want to capture it, you will take the risk that program code errors (bugs) are hidden and invisible during running. During program testing, the stack trace printed by the system often allows you to locate and modify errors in the Code more quickly. Some programmers suggest capturing the runtime exception and recording it in the log. I am opposed to this. The downside is that you must browse the log to find out the problem, but the testing system (such as Unit Test) used to Test the program cannot directly capture the problem and report it.

Capturing a runtime exception in a program brings about more problems: Which runtime exceptions should be captured? When will it be captured? Runtime exception does not need to be declared. How do you know if runtime exception is to be captured? Do you want to see that every time a method is called in a program, the try/catch Block is used?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.