I believe everyone will throw exceptions, right? Just do this:
throw new RuntimeException("didispace.com");
However, there are some situations in the development process, we need to test whether the program's processing logic for exceptions is correct. At this time, we need to actively throw exceptions when the program is running to trigger the relevant logic to verify the correctness. This is a common scenario. There are: whether the transaction will be rolled back , unified exception handling at the Web layer, and so on.
At this time, how do you create exceptions to support your debugging?
Let me take an example of transaction processing in the Spring Boot tutorial I wrote before as a scenario, and show you some common debugging operations and more elegant operations that I will talk about today.
Case description
Let's first introduce the following scenario, which is a database operation case implemented with Spring Data JPA . On the right side UserService
there is a transaction operation, which contains 5 insert statements for the User table.
Because the @Transactional
annotation exists, the data insertion under the saveSomeUsers
function either succeeds or fails. Success is a good test. If the test fails, we need to make this function throw an exception to trigger the rollback operation.
Roll up your sleeves and throw
In order to throw an exception to verify whether the transaction can be rolled back, many small partners do this:
Throwing an exception manually in this function is very rude and direct, and it can accomplish the goal. Although this method is ok as a scenario in unit testing, it is not so elegant if it is done in a complex business process, because you have to delete it after testing, and if you forget it, write it directly a bug.
Throw exceptions gracefully
In fact, IDEA provides the function of throwing exceptions freely. You only need to right-click the Reset Frame position of the rollback operation introduced a few days ago during Debug, and you can see the operation marked by the arrow in the following figure Throw Exception
.
Then in the popup, you can write the exception you want to throw:
Is it very simple? Quickly open IDEA and give it a try! The video tutorials here are also updated synchronously, click to view , I am serializing the video content of IDEA topic , interested friends can follow me!
Welcome to my public account: Programmer DD. Learn about cutting-edge industry news for the first time, share in-depth technical dry goods, and obtain high-quality learning resources
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。