Java exception Encapsulation (own definition error code and description, attached source) __java

Source: Internet
Author: User

Really work to find that the exception in Java in the real work of the use is very common. It's important to know when to throw something out of the ordinary.

Of course, the real work inside the initiative thrown out of the exception is a separate loaded, you can define the error code and description of the exception.

The following small Bao for you to introduce a Java exception simple encapsulation example.

Before giving an example of abnormal loading, we need to popularize the concept of checked anomaly and unchecked exception in Java. I. Checked anomalies and unchecked anomalies

The reason why we are so clear about the concept of checked anomaly and unchecked anomaly is that our exception is inherited unchecked abnormal runtimeexception. There's no harm in understanding it.

Checked Exception:

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

Must be handled explicitly in your code. For example, try-catch block processing, or to add a throws description of the method, throw the exception to the upper layer of the call stack.

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

Unchecked Exception:

Indicates an error, and the program's logic is wrong. Are runtimeexception, such as IllegalArgumentException, NullPointerException, and IllegalStateException.

You do not need to explicitly capture unchecked exceptions in your code to do processing.

Inherits from Java.lang.RuntimeException (and Java.lang.RuntimeException inherits from Java.lang.Exception).

Look at the following anomaly structure diagram and perhaps deeper layers:

second, abnormal separation of the case

2.1, add an enumeration Luoerrorcode.java as follows:

Package Com.luo.errorcode;

public enum Luoerrorcode {

    null_obj ("LUO001", "Object is empty"),
    error_add_user ("LUO002", "Add User Failed"),
    Unknown_ ERROR ("LUO999", "system 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;
    }
}

Pay attention to ... Here we rewrite the Luoerrorcode tostring method, as to why it is so, the following will be mentioned, objective please continue to see.

2.2, create an exception class Businessexception.java, inherit 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 1th is that it inherits runtimeexception, because generally our business exception is run-time exception. 2nd, the constructor here calls the parent method super (Obj.tostring ()), which is the reason for rewriting the Luoerrorcode's ToString method, and if you don't understand it, you'll see after that.

2.3, test class 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)
        ;
    }
}}

Run Result:

add: In our actual project, for example, if someone calls your interface, you may need to see if the object he passed in is not empty, first of all, if the object passed is null to give a friendly hint "[LUO001] object is empty", otherwise the following code estimates that there will be null pointer exception.

The General company will be divided into a basic framework, abnormal separation is part of it, of course, their separation of abnormal is certainly more complex than my example, so this example is for reference only.

If you don't bother copy and paste, download the project directly:

http://download.csdn.net/detail/u013142781/9422684

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.