One way
try....catch...finally, catch and handle exceptions in catch
Mode two
Set the default global exception handler.
In case of any abnormality, throw upward one by one,
In this process, if the exception is caught and handled by catch, it will be OK;
If there is no corresponding catch to catch and handle exceptions, they will be finally thrown to dispatcher servlet and web server. The processing method of web server is to send back a bunch of error information and display it to the user in the browser.
We can set a default global exception handler. When it is thrown to the dispatcher servlet, the dispatcher servlet calls the default global exception handler to handle the exception.
It is equivalent to setting a global catch.
Create a new class and implement the HandlerExceptionResolver interface
@Component public class MyExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView mav = new ModelAndView("error"); mav.addObject("msg", e.getMessage()); return mav; } }
- You need to put this class into the Spring container, which can be configured with < bean > or annotated with @ Component.
- The exception object will be passed in automatically. We can get the exception information from this exception object
- The return value is of ModelAndView type. This class will intercept the unwanted exception before the jvm, call resolveException() to handle it, and respond with the specified view. You can pass exception information to the view.
Originally, it would display a bunch of error messages on the browser page, all in professional terms or in English, which is very unfriendly to users.
In this way, you can specify the view and customize the information to be displayed, which is very user-friendly.
The disadvantage is that the uncaught exception is handled uniformly. No matter what kind of exception, the handling method is the same, too general.
Mode 3
Use a custom exception class.
(1) Create a new package, com.chy.exception, to put custom exception classes. Then write several custom exception classes.
For example, transfer may occur:
- Insufficient balance, NoMoneyException
- The opposite account does not exist, UserNotFoundException
- Account frozen, frozen exception
public class NoMoneyException extends Exception{ private String msg; public NoMoneyException(String msg) { super(); this.msg = msg; } public String getMsg() { return msg; } }
Provide String type String to represent exception information, corresponding constructor to create exception object, and corresponding getter method to obtain exception information.
Create the other 2 exceptions in the same way.
When alt+insert, do not use String message, which is a parameter of the base class Exception, indicating the error message of code execution. It's OK to use our own variables.
Our custom exception is not to deal with code errors. Just try...catch the code errors directly. There is no need to customize the exception.
Custom exceptions are used to prompt users in a friendly way. For example, if the dao layer finds that the balance is insufficient, I will throw a NoMoneyException directly. There is no error in the code execution itself, and exceptions are thrown manually.
(2) Throw exception in dao layer
public class UserDao{ public void transfer(int to,int from,double amount) throws NoMoneyException,UserNotFoundException,FrozenException { //Connection database query is omitted here //..... //Sorry, your credit is running low if (Sorry, your credit is running low){ throw new NoMoneyException("Your current balance xx Yuan, the balance is insufficient, unable to complete the transfer!"); } //The opposite account does not exist if (The opposite account does not exist){ throw new UserNotFoundException("Account of the other party xxxxxxxxxx Non-existent!"); } //Opposite account is blocked if (Opposite account is blocked){ throw new FrozenException("Account of the other party xxxxxxxxxx Frozen, unable to transfer to the opposite party!"); } //.... } }
Instead of using catch, throw an exception on the method signature.
The method signature of the corresponding service layer should also be thrown out:
public class UserService{ public void transfer(int to,int from,double amount) throws NoMoneyException,UserNotFoundException,FrozenException { //call dao layer } }
(3) Handling exceptions in controller
@org.springframework.stereotype.Controller public class UserController { @RequestMapping("/transfer") public ModelAndView transfer() { try { //call service layer }catch (NoMoneyException e){ //Can call e.getMsg()Get the customized exception information, forward it to a view, and transfer the data //..... }catch (UserNotFoundException e){ //.... }catch (FrozenException e){ //...... } } }
It can also be handled in the global exception class:
@Component public class MyExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //Handle according to the type of exception, if (e instanceof NoMoneyException){ //..... } if (e instanceof UserNotFoundException){ //..... } if (e instanceof FrozenException){ //..... } } }
If the processing methods are the same, such as forwarding to a view or explicitly customizing the error information, you don't need to write if judgment to distinguish the exception types and write directly for processing.
You can also call views and transfer data.
Mode three is usually used in combination with try...catch:
- try...catch handles code errors, such as file not found, null pointer exception, etc., and code execution itself has problems;
- Mode 3 is mainly used for our custom errors, and the code execution itself is no problem.