Summary of "Turn" Java exception and analysis of exception mechanism of spring transaction processing

Source: Internet
Author: User
Tags stack trace throw exception

Concepts of exceptions and Java exception architectures

An exception is an error that occurs while the program is running. This article mainly teaches the Java language exception processing. The exception processing framework of Java language is an important embodiment of the robustness of Java language.

ThorwableClass for all exceptions and errors, there are two subclasses Error and Exception , respectively, represent errors and exceptions.
Where the exception class is Exception divided into run-time exceptions (runtimeexception) and non-runtime exceptions , the two exceptions are very different, also known as no check exception (unchecked Exception)
and check for exceptions (Checked Exception).

    • Run-time Exception---> uncheckedexception
    • Non-run-time Exception--->checkedexception

Error and Exception
    • ErrorErrors that the program cannot handle, such as OutOfMemoryError , and ThreadDeath so on. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread.

    • ExceptionIs the exception that the program itself can handle, which is divided into two major classes, runtime exceptions , and non-runtime exceptions . These exceptions should be handled as much as possible in the program.

2. Run-time exceptions and non-runtime exceptions

Run-time exceptions are runtimeexception classes and their subclass exceptions, such as

    • NullPointerException,
    • Indexoutofboundsexception

These exceptions are not checked for exceptions (uncheckedexception), which can be either captured or not handled in the program. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view. compilation is possible .

A non-runtime exception is an exception other than RuntimeException, and the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through . such as IOException, SqlException, and user-defined exception exceptions, generally do not customize check exceptions.

Exception capture and handling

Java exception capture and processing is a difficult thing to grasp, if handled improperly, not only will make the program code readability greatly reduced, and caused the system performance is low, even caused some difficult to find errors.

Java exception handling involves five keywords, namely:,,, try catch finally throw , throws .

Problems to be noted in try, catch, finally three statement blocks trycatchfinallyThree block of statements cannot be used alone, three can be composed try...catch...finallytry...catchtry...finallyThree structures, catch statements can have one or more, finally statements up to one. The scope of the variables in the try, catch, finally three code blocks is within the code block, independent of each other and not accessible to each other. If you want to be accessible in three blocks, you need to define the variables outside of those blocks. Multiple catch blocks, only one of the exception classes is matched and the catch block code is executed, and no other catch blocks are executed, and the order of matching catch statements is from top to bottom. throw, throws keyword

throwThe keyword is used inside the method body to throw an Throwable exception of a type.

If you throw a Check for exceptions, you You should also declare the type of exception that the method might throw in the method header。 The caller of the method must also check the exception that is thrown by the handle. If all of the methods are thrown at layers, the JVM will eventually be processed and the processing is simple, which is to print the exception message and stack information. If an error or runtimeexception is thrown, the caller of the method can choose to handle the exception. The translation of the exception is described below.

When a run-time exception is thrown, the program can choose to process and not process

Public static span class= "DT" >void maintry {filereader file = new filereader (" D:/entitycode "); span class= "kw" >catch (FileNotFoundException e) {e.printstacktrace (); span class= "kw" >throw new RuntimeException (); }} 

Throws a non-runtime exception, the program must be processed, can continue to throw out, or capture

Public Static void main (string[] args) throws FileNotFoundException {try {FileReader file = span class= "kw" >new filereader ( d:/ Entitycode "); } catch (FileNotFoundException e) {e.printStackTrace ( ); throw new FileNotFoundException (); }} 
The throws keyword is used in the method declaration section outside the method body to declare that the method may throw some exceptions. Only if a check exception is thrown, the caller of the method must handle or re-throw the exception. When the caller of the method is unable to handle the exception, it should continue to throw, rather than swallowed generally print the stack information in the catch block and do a little bit of processing. Here is a simple example of a common approach in the Throwable class
    • getCause(): Returns the reason for throwing an exception. If cause does not exist or is unknown, NULL is returned.
    • getMessage(): Returns the message information for the exception.
    • printStackTrace(): The stack trace of the object is output to the error output stream as the value of the field System.err.
The general principle of exception handling can deal with the early processing, throw not to be able to deal with the idea of digestion or conversion to runtimeexception processing. Because it is problematic for an application system to throw a large number of exceptions, it should be possible to control the occurrence of exceptions from the point of view of the program development. For check exceptions, it is better to cast to runtimeexception if it cannot be handled effectively. This also allows the upper-level code to have a choice-can be handled or not processed. For an application system, it should have its own set of exception processing framework, so that when the exception occurs, you can also get a unified processing style, the elegant exception information to the user. Java Exception Summary Java distinguishes exceptions into errors and Exception,error is an error that the program is unable to handle, and exception is an error that the program can handle. Exception handling is for the robustness of the program. Exceptions can be handled on the handle, cannot be processed on the throw, and eventually unhandled exception the JVM will handle. Exceptions can be propagated, or they can be translated from one another, but the direction of a reasonable anomaly translation should be chosen as needed. For an application system, it is very important to design a set of good exception handling system. This should be taken into account when designing the system. ExceptionGenerally divided into Checked异常And Runtime异常All RuntimeExceptionInstances of classes and their subclasses are called Runtime异常, exceptions that are not part of this category are called CheckedException。 Spring transaction rollback with exception spring is a transaction-managed method that needs to be thrown Non-check exception, which is a run-time exception to roll back

For non-checked class exceptions can not be captured, and check-type exceptions must be handled with a try statement block or the exception to the superior method processing is necessary to write code to deal with it. So you have to catch the exception at the service and then throw it again , so the transaction just works.

In the spring transaction management environment, using unckeckedexception can greatly simplify the handling of exceptions by declaring the possible exceptions at the transaction level (the exception here can be a custom unckecked exception system). In all the middle tier just need simple throws can, do not need to capture and processing, directly to the top layer, such as the UI layer and then the exception of the capture and processing

With @transactional in front of the service class, declare that all methods of the service require transaction management. Each business method starts with a transaction open.

Spring defaults to a transaction rollback of the run-time exception (RuntimeException). This exception is unchecked if you encounter an checked accident, do not roll back.

How to change the default rule:

    • 1 Let checked exception also rollback: Add @Transactional before the whole method (Rollbackfor=exception.class)

    • 2 Let unchecked exception not rollback: @Transactional (Notrollbackfor=runtimeexception.class)

    • 3 (Query-only) methods that do not require transaction management: @Transactional (propagation=propagation.not_supported)

Note: If the exception is try{}catch{}, the transaction is not rolled back, and if you want the transaction to roll back, you must throw the Try{}catch{throw Exception} out.

A unified exception hierarchy is required to provide a service abstraction. The most important thing is org.springframework.dao.DataAccessException and its subclasses. It is important to emphasize that spring's anomaly mechanism focuses on the application programming model. Unlike SqlException and other data access APIs, spring's exception mechanism is to allow developers to use the least, clearest code. DataAccessException and other underlying exceptions are non-check exceptions (unchecked exception). One of the principles of spring is that grassroots anomalies should be non-censorship exceptions. The reasons are as follows:

    • Grass-roots anomalies are generally not recoverable.
    • An inspection exception will reduce the value of the exception hierarchy. If the underlying exception is checked, then you need to add a catch statement to capture it everywhere.
    • Try/catch code blocks are lengthy and confusing, and do not add much value. Using check exceptions is good in theory, but it does not seem to be the case. Hibernate3 will also switch from an inspection exception to a non-check exception.
Transferred from: https://www.cnblogs.com/leihuazhe/p/7735416.html

Summary of "Turn" Java exception and analysis of exception mechanism of spring transaction processing

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.