Java exception encapsulation (custom error codes and descriptions, with source code)

Source: Internet
Author: User

Java exception encapsulation (custom error codes and descriptions, with source code)

Only when I really work can I find that exceptions in Java are still very common in real work. You must know when to throw an exception.

Of course, all the exceptions actively thrown during the real work are sub-installed. You can define the error code and description.

The following is an example of Java exception simple encapsulation.

Before providing an exception Package example, we need to popularize the concepts of checked and unchecked exceptions in Java.

I. checked and unchecked exceptions

The reason for this is to let everyone know the concepts of checked exceptions and unchecked exceptions is that our exceptions will inherit the RuntimeException of the unchecked exception. There is no harm in understanding it.

Checked exception:

Invalid, not predictable in the program. For example, invalid user input, file does not exist, network or database connection error. These are external reasons, none of which can be controlled within the program.

Must be explicitly processed in the code. For example, try-catch Block Processing, or add throws to the method to throw the exception to the upper layer of the call stack.

Inherited from java. lang. Exception (except java. lang. RuntimeException ).

Unchecked exception:

Indicates the program logic error. Is a subclass of RuntimeException, such as IllegalArgumentException, NullPointerException, and IllegalStateException.

You do not need to explicitly capture unchecked exceptions in the Code for processing.

Inherited from java. lang. RuntimeException (while java. lang. RuntimeException inherited from java. lang. Exception ).

The following exception structure may have a deeper sense of attention:

Ii. Abnormal sub-assembly instance

2.1 Add an enumeration LuoErrorCode. java as follows:

Package com. luo. errorcode; public enum LuoErrorCode {NULL_OBJ ("LUO001", "the object is empty"), ERROR_ADD_USER ("LUO002", "failed to add a user"), UNKNOWN_ERROR ("LUO999 ", "The system is busy. Please try again later .... "); private String value; private String desc; private LuoErrorCode (String value, String desc) {this. setValue (value); this. setDesc (desc);} public String getValue () {return value;} public void setValue (String value) {this. value = value;} public String getDesc () {return desc;} public void setDesc (String desc) {this. desc = desc ;}@ Override public String toString () {return "[" + this. value + "]" + this. desc ;}}

Note !!! Here we have rewritten the toString method of LuoErrorCode. As to why, we will refer to it later.

2.2 create an exception class BusinessException. java that inherits RuntimeException:

package com.luo.exception;public class BusinessException extends RuntimeException {    private static final long serialVersionUID = 1L;    public BusinessException(Object Obj) {        super(Obj.toString());    }}

The code here is short, but there are two points to note !!! The first point is that it inherits RuntimeException, because our business exceptions are generally runtime exceptions. Second, the constructor calls the parent method super (Obj. toString (); this is why the toString method of LuoErrorCode is rewritten. If you still don't understand it, you will understand it after reading it.

2.3 Test ExceptionTest. java:

package com.luo.test;import com.luo.errorcode.LuoErrorCode;import com.luo.exception.BusinessException;public class ExceptionTest {    public static void main(String args[]) {        Object user = null;        if(user == null){            throw new BusinessException(LuoErrorCode.NULL_OBJ);        }    }}

Running result:

Supplement: in our actual project, for example, if someone calls your interface, you may need to check whether the object it passes is empty, first, let's determine if the passed object is empty and a friendly prompt "[LUO001] object is empty" is displayed. Otherwise, the code below will probably encounter a null pointer exception.

Generally, companies will package a basic framework, and the exception package is part of it. Of course, they are more complicated than my example, so this example is for reference only!

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.