Java Exception Handling Mechanism and differences between the two exceptions

Source: Internet
Author: User
Tags finally block stack trace
The Java exception handling mechanism mainly relies on five keywords: Try, catch, finally, throw, and throws.
The try keyword is followed by a code block enclosed in curly brackets, or try block for short. Similarly: The following is also called the corresponding block.
It can set the code that causes exceptions. Catch corresponds to the exception type and a code block, which indicates that the catch block is used to process this type of code block. You can also use a Finally block to reclaim the physical resources opened in the try block. The exception mechanism ensures that the Finally block is always executed. The throws keyword is mainly used in the method signature to declare the exceptions that the method may throw, and throw is used to throw an actual exception. Throw can be used as a statement separately, the Java Exception Handling object that throws a specific exception can make the program more fault tolerant and more robust. When the program encounters an unexpected situation, the system automatically generates an exception object to notify the program, thus separating "business function implementation code" from "error processing code" to provide better readability. If an exception occurs when executing the business logic code in the try block, the system automatically generates an exception object that is submitted to the Java Runtime Environment. This process is called throw) exception. When the Java Runtime Environment receives an exception object, it looks for a catch block to handle the exception object. If a suitable Catch Block is found and the exception is handed over to it for processing, this process is called a catch exception; if no catch block can be found in the Java Runtime Environment, the runtime environment ends and the program exits. Use finally to reclaim physical resources when the program opens some physical resources (database connections, network connections, and disk files) in the try block, these physical resources must be recycled. To ensure that the physical resources opened in the try block can be recycled, The Exception Handling Mechanism provides a Finally block. No matter whether the code in the try block is abnormal or whether the Catch Block is executed, finally blocks are always executed. In the exception handling structure syntax, only try blocks are required. Once try blocks are not available, catch and finally blocks cannot appear. If try blocks exist, catch blocks and finally blocks are optional. However, either of them must have at least one. Multiple catch blocks can also appear at the same time. The Catch Block must be behind the try block, and the finally must be behind the Catch Block (if any). When the Java program executes the try block or catch block, it encounters a return or throw statement, both of these statements will immediately end the method, but the system does not immediately execute the two statements. Instead, it looks for whether the exception handling process contains finally blocks, if no Finally block program executes the return or throw statement immediately, the method is terminated. Otherwise, the system will immediately execute the Finally block. Only after the Finally block is executed will the system jump back and execute the try block again to catch the return or throw statement in the block, if a return or throw statement exists in the Finally block at the same time, the Finally block has terminated the method. Naturally, the system does not jump back to execute the return or throw statement in the try or catch block. The idea of throwing an exception using throws declaration is: the current method does not know how to handle this exception. The exception should be handled by the upper-level caller, if the main method does not know how to handle this exception type. You can also use the throws declaration to throw an exception and hand it over to javajvm for processing. JVM Exception Handling Method: Print exception tracing stack information and terminate program operation
Runtime exception and checked exception
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. * 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.

* 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 checked
Exception, your program can capture it and handle it correctly: for example, you are prompted to re-enter it. 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 Runtime
Exception is recorded 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. For runtimeexception type exceptions, javac
It is impossible to determine which functions (or code in which regions) may throw such exceptions through static syntax check during compilation (which depends entirely on the runtime status or runtime State) can it be understood as non_checked ?, Because of this, the "must be caught or declared to be thrown" rule in the Java Exception Handling model does not apply to runtimeexception (so there is a strange compilation phenomenon mentioned above, this is also a special rule ). However,
Java virtual machines must effectively capture and handle such exceptions. Of course, runtimeexception can also be explicitly thrown by the programmer. For program reliability, for some code regions that may encounter "runtimeexception, it is best for programmers to promptly handle these unexpected exceptions, that is, catch (runtimeexcetion) or catch (exception) to catch them.
Summary:

The root class of all exceptions is Java. Lang. throwable. Two subclasses are derived under throwable: Error and exception. Error indicates that recovery is not a serious problem that is impossible but difficult. For example, if the memory overflows, it is impossible to expect the program to handle such a situation. Exception indicates a design or implementation problem, that is, it indicates that if the program runs normally, it will never happen.
An exception indicates an abnormal state that may occur during the running of the program. An exception indicates an exception that may occur during common operations on the virtual machine. It is a common running error. The Java compiler requires that methods must declare and throw possible non-runtime exceptions, but do not require that they be declared as caught runtime exceptions.
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.