Two exceptions for Java runtimeexception and checkedexception

Source: Internet
Author: User
Tags finally block terminates

The Java exception handling mechanism relies mainly on try,catch,finally,throw,throws five keywords. The   try keyword is immediately followed by a block of code enclosed in curly braces, called the try block. Similarly: The following is also known as the corresponding block.   It can contain code that throws an exception. A catch corresponds to an exception type and a block of code that indicates that the catch block is used to handle this type of code block. can also be followed by a finally block, finally block is used to reclaim the physical resources opened in the try block, the exception mechanism will ensure that the finally block is always executed. The throws keyword is primarily used in method signatures to declare exceptions that may be thrown by the method, while throw is used to throw an actual exception, throw can be used as a statement alone, and throwing a specific exception to the object Java exception handling can make the program more tolerant and robust.  When an unexpected scenario occurs, a exception object is automatically generated to notify the program, allowing for better readability by separating "business function implementation Code" and "error handling code". If an exception occurs when executing the business logic code in a try block, the system automatically generates an exception object that is presented to the Java runtime, which is called a throw (throw) exception.  When the Java runtime receives an exception object, it looks for a catch block that handles the exception object, which is called a catch exception if the appropriate catch block is found and the exception is given to it, and if the Java runtime cannot find a catch block to catch the exception, the run environment terminates and the program exits.  Use finally to reclaim physical resources some physical resources (database connections, network connections, and disk files) that the program opens in a try block must show recycling. To ensure that physical resources opened in a try block are recoverable, the exception handling mechanism provides a finally block, which is always executed regardless of whether the code in the try block has an exception or if it is executed in any catch block. Only try blocks are required in the exception-handling structure syntax, and once there is no try block, catch and finally blocks cannot appear, and if a try block exists, both the catch block and the finally block are optional. But there must be at least one. Multiple catch blocks can also appear at the same time. The catch block must be behind a try block, and finally must be behind a catch block (if one exists), and when the Java program executes a try block, catch block, it encounters a return statement or a throw statement, both of which cause the method to end immediately. But the system does not immediately execute the two statements, but instead looks for the differentWhether the process contains a finally block, or if no finally block program immediately executes a return statement or a throw statement, the method terminates. Conversely, the system executes the finally block immediately--only after the finally block is executed does the system jump back to execute the try block, return or throw statement in the catch block, and if there is also a return or throw statement in the finally block.  Then the finally block has terminated the method, and naturally no system jumps to execute the return or throw statement in the try or catch block. The idea of throwing an exception using the throws declaration is that the current method does not know how to handle the exception, which should be handled by the caller at the top level, and if the main method does not know how to handle the exception type.  You can also use the throws declaration to throw an exception, handing the exception to JAVAJVM processing. JVM Handling of Exceptions: Print exception tracking 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 exception are derived from the Java.lang.Exception class, and the runtime Exception is derived from the Java.lang.RuntimeException or Java.lang.Error class.

Their differences are manifested in two ways: both institutional and logical.

First, the mechanism
Their differences in mechanism are shown at two points: 1. How to define a method; 2. How to handle the thrown exception. * Runtime Exceptions:

No declaration is required when defining a method to throw runtime exception;

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 classes.

* Checked Exceptions:

When defining a method, you must declare all checked exception that may be thrown;

When calling this method, it must catch its checked exception, or it will have to pass its exception;

Checked exception is derived from the Java.lang.Exception class. Second, logically
From a logical point of view, checked exceptions and runtime exception are used for different purposes. Checked exception is used to indicate an exception condition that a caller can handle directly. Runtime exception is used to indicate a program error that cannot be handled or recovered by the caller itself.

  Checked exception forces you to capture it and deal with this abnormal situation. Take the Java.net.URL Class Builder (constructor) as an example, and each of its builders throws malformedurlexception. Malformedurlexception is a kind of checked exception. Imagine that you have a simple program that prompts the user to enter a URL and then downloads a Web page through the URL. If the user enters a URL with an error, the builder throws a exception. Since this exception is checked exception, your program can capture it and handle it correctly: for example, prompting the user to re-enter it.   All in all, when a checked exception is thrown during a program's operation, only the caller who can handle the exception appropriately should use Try/catch to capture it. For runtime exception, it should not be captured in the program. If you want to capture it, you take the risk that an error (bug) in the code of the program is obscured and cannot be detected in the run. Because during program testing, the system prints a call stack path (StackTrace) that often allows you to quickly find and modify errors in your code. Some programmers recommend capturing the runtime exception and logging it in log, which I oppose. The downside to this is that you have to browse through the log to find the problem, and the test system used to test the program (such as unit test) cannot directly capture the issue and report it.              for runtimeexception types of exceptions,  javac It is not possible to determine exactly which functions (or areas of code) can throw such exceptions (which depends entirely on the runtime state, or what the run State determines) by the static syntax detection at compile time non_checked can? , and 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 earlier, which is also a special rule). However, Java virtual machines need to effectively capture and handle such exceptions. Of course, runtimeexception can also be explicitly thrown by programmers, and for the sake of program reliability, there may be "Runtime exceptions" (runtimeexception) "Code area where programmers are best able to handle these unexpected exceptions in a timely manner, that is, catch (runtimeexcetion) or catch (Exception) to capture them. Summary: The root class for all exceptions is java.lang.throwable,throwable, which also derives two subclasses: Error and exception. Error indicates that recovery is not an impossible but difficult situation for a serious problem. For example, a memory overflow, it is impossible to expect the program to handle such a situation, exception represents a design or implementation problem, that is, it means that if the program is running normally, it will never happen. An exception represents an unhealthy state that may occur during a program's run, and a run-time exception that represents an exception that might be encountered in a virtual machine's usual operation is a common run-down error. The Java compiler requires the method to declare a non-runtime exception that might occur, but does not require that a run-time exception that is thrown as caught must be declared.

Two exceptions for Java runtimeexception and checkedexception

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.