What are the similarities and differences between Java Runtime Exceptions and general exceptions?

Source: Internet
Author: User

Throwable is the parent of error handling in all Java programs, and there are two types of assets: Error and Exception.

Error: Indicates an unexpected fault detected by the JVM, because this is a serious error at the JVM level, which prevents the JVM from continuing, so this is not a snap and cannot take any recovery action, at most, only error messages can be displayed.

Exception: Represents recoverable exceptions, which can be captured.

Java provides two main types of exceptions: Runtime exception and checked exception. The checked exception is the IO exception that we often encounter, and the SQL exception is the exception. For this exception, the JAVA compiler enforces that we must catch the exceptions that occur. So, in the face of such anomalies whether we like it or not, we can only write a lot of catch blocks to deal with possible exceptions.

But another exception: Runtime exception, also known as runtime exception, we can not handle. When such an exception occurs, it is always taken over by the virtual machine. For example: No one has ever dealt with a nullpointerexception exception, which is a run-time exception, and this exception is one of the most common exceptions.

When a run-time exception occurs, the system throws the exception all the way to the top and continues to experience processing code. If there is no processing block, to the topmost level, if it is multithreading is thrown by Thread.run (), if it is a single thread is thrown by main (). Once thrown, the thread exits if it is a thread. If the exception is thrown by the main program, then the entire program exits. Runtime exceptions are subclasses of the Exception, and there are general exceptions that can be handled by Catch blocks. It's just that we're not dealing with him. That is, if you do not handle a run-time exception, then a run-time exception occurs, either the thread aborts or the main program terminates.

If you do not want to terminate, you must catch all run-time exceptions and never let the processing thread exit. Abnormal data in the queue, the normal processing should be to discard the abnormal data, and then log. The handling of normal data should not be affected by abnormal data. This can be a good application in this scenario, but it does not mean that you should do so in all scenarios. If, in other scenarios, you encounter some errors, if you exit the program better, then you can ignore the runtime exception, or by the exception of the handling of explicit control program exit.

One of the goals of exception handling is to recover the program from the exception.

Transferred from: http://blog.csdn.net/yakihappy/archive/2009/03/11/3979883.aspx

An exception indicates 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-time error. The Java compiler requires that a method declare a non-runtime exception that might occur, but does not require that the throw of an uncaught runtime exception be declared.

The following is a brief explanation of Java exceptions:

1. Exception mechanism

1.1

The exception mechanism is what the program does when an error occurs. Specifically, the exception mechanism provides a secure channel for the program to exit. When an error occurs, the program execution process changes and the control of the program is transferred to the exception handler.

1.2

The traditional way of dealing with exceptions is that the function returns an extraordinary result to indicate an exception (usually this extraordinary result is commonly called), and the program that invokes the function is responsible for examining and parsing the results returned by the function. This is a disadvantage: for example, the function returns 1 for an exception, but if the function does return 1, the correct value will be confused, the readability is reduced, the program code is mixed with the code that handles the exception, and the program that invokes the function parses the error, which requires the client programmer to have a deep understanding of the library function. .

1.3 Process of exception handling

1.3.1 encounters an error, the method ends immediately, does not return a value, and throws an exception object

1.3.2 The program that calls the method does not continue, but instead searches for an exception handler that can handle the exception and executes the code in it

2 Classification of exceptions

2.1 Classification of exceptions

2.1.1

The continuation structure of the exception: base class for Throwable,error and exception continue exception throwable,runtimeexception and IOException, The concrete runtimeexception continues to runtimeexception.

2.1.2

Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).

2.2 Characteristics of each type of anomaly

2.2.1 Error System

The error class system describes the internal errors and resource exhaustion scenarios in the Java operating system. Applications should not throw objects of this type (typically thrown by virtual machines). In the event of such an error, there is no other way of doing anything other than trying to get the program to exit safely. So, when it comes to programming, Should pay more attention to exception system.

2.2.2 Exception System

Exception system includes RuntimeException system and other non-runtimeexception systems.

2.2.2.1 RuntimeException

The runtimeexception system includes wrong type conversions, array cross-border access, and attempts to access null pointers, and so on. The principle of dealing with runtimeexception is that if runtimeexception is present, it must be a programmer's fault. For example, You can avoid array out-of-bounds access exceptions by examining array subscripts and arrays boundaries.

2.2.2.2 Other (IOException, etc.)

Such exceptions are generally external errors, such as trying to read data from the end of a file, which is not an error in the program itself, but an external error that occurs in the application environment.

2.3 Differences from C + + exception classifications

2.3.1

In fact, the runtimeexception of this class name in Java is inappropriate because any exception is present at runtime. (Errors that occur at compile time are not exceptions, in other words, exceptions are to resolve errors that occur when the program runs).

2.3.2

Logic_error in C + + is equivalent to RuntimeException in Java, and Runtime_error is equivalent to an exception of non-runtimeexception types in Java.

3 How to use exceptions

3.1 Declaring a method throws an exception

3.1.1 Syntax: throws (slightly)

3.1.2 Why declare a method to throw an exception?

method is just as important as the type of the method return value. Assuming that the method throws an exception and does not declare that the method throws an exception, the client programmer can call this method and not write the code that handles the exception. Then, once an exception occurs, the exception is not resolved by the appropriate exception controller.

3.1.3 Why is the exception thrown must have been checked for exceptions?

RuntimeException and error can be generated in any code, they do not need to be shown by the programmer to throw, and in the event of an error, the corresponding exception will be automatically thrown. Just checking for exceptions is thrown by the programmer, which is divided into two cases: the client programmer calls the library function that throws the exception ( The exception to the library function is thrown by the library programmer; The client programmer throws an exception using the throw statement itself. When encountering error, programmers are generally powerless; when encountering runtimeexception, it must be a logic error in the program, to modify the program (equivalent to debugging a method); Only checked exceptions are the programmer's concern, and the program should and should only throw or handle checked exceptions.

3.1.4

Attention: A subclass method that overrides a method of a parent class cannot throw more exceptions than a parent class method, so sometimes a method of the parent class is designed to declare an exception, but the code of the actual implementation method does not throw an exception, and the purpose is to make it easier for the subclass method to overwrite the parent class method by throwing an exception.

3.2 How to throw an exception

3.2.1 Syntax: throw (slightly)

What exception does 3.2.2 throw?

For an exception object, the really useful information is the exception object type, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, then the class name is the only useful information. So, when you choose what exception to throw, The key is to choose the class name of the exception to clarify the exception of the class.

3.2.3

Exception objects usually have two constructors: one is a parameterless constructor, and the other is a constructor with a string that acts as an additional description of the exception object in addition to the type name.

3.2.4

Create your own exception: you need to create your own exception when the Java built-in exception does not explicitly describe the exception. It is important to note that the only useful thing is the type name information, so do not expend effort on the design of the exception class.

3.3 Catching exceptions

If an exception is not handled, then, for a non-graphical interface program, the program will be aborted and output exception information, for a graphical interface program will also output the exception information, but the program does not abort, but return to the user interface processing loop.

3.3.1 syntax: Try, catch, and finally (slightly)

The controller module must be immediately behind the try block. If an exception is thrown, the exception control mechanism searches for the first controller that matches the type of the exception and then it goes into that catch.

The exception has been controlled. Once the catch clause ends, the search for the controller stops.

3.3.1.1 Catching multiple exceptions (emphasis on syntax and snapping order) (slightly)

3.3.1.2 finally's usage and exception handling flow (slightly)

What does 3.3.2 do with exception handling?

For Java, exception handling does not need to reclaim memory because of garbage collection. But there are still some resources that need to be collected by programmers, such as files, web connections, and pictures.

3.3.3 should I declare a method to throw an exception or catch an exception in a method?

Principle: Catching and dealing with exceptions that know how to handle them, and passing on those that do not know how to handle them

3.3.4 throws an exception again

3.3.4.1 Why do you want to throw an exception again?

In this level, only a subset of the content can be processed, some processing needs to be done in a higher level environment, so the exception should be thrown again. This allows each level of the exception handler to handle the exceptions it can handle.

3.3.4.2 Exception Handling Process

The catch block corresponding to the same try block will be ignored, and the thrown exception will go to the higher level.

4 other questions about the exception

4.1 Over-use exceptions

First, the use of exceptions is convenient, so programmers are generally no longer willing to write code to handle the error, but simply throw an exception. This is not true, and for fully known errors, you should write code that handles this error, increasing the robustness of the program. In addition, the efficiency of the anomaly mechanism is poor.

4.2 Separating the exception from the normal error area

For common, completely consistent errors, code that handles this error should be written to increase the robustness of the program. Only external, unpredictable, and predictable run-time errors require an exception to be used.

4.3 information contained in the exception object

In general, the only useful information for an exception object is type information. However, this string can also be used as additional information when using the exception string constructor. Call the exception object's GetMessage (), toString (), or printstacktrace () The method can get the additional information of the exception object, the class name and the call stack separately. And the latter contains information that is the superset of the previous one.

Transferred from: http://www.zhiweinet.com/jiaocheng/2008-09/1452.htm

What are the similarities and differences between Java Runtime Exceptions and general 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.