Java custom Exception

Source: Internet
Author: User

Java custom Exception

Here we will summarize the Java Exception and implement a custom Exception class.

Summary:

  1. Throwable objects can be divided into two types: Error (indicating Compilation Time and system errors) and Exception (Exceptions thrown during Java class libraries, user methods, and runtime faults ).
  2. Exception is divided into two types: checked exceptions (such as IOException and SQLException. Exceptions that need to be forcibly checked during compilation must be handled using the try, catch, and finally keywords during compilation; otherwise, an error will be reported .); Runtime exceptions (such as ArithmeticException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException, and NullPointerException. The compiler does not check for such exceptions .)
  3. Best practices for exception handling in Java programming [4]:
    • Checktype exceptions are used for recoverable errors and non-checktype errors are used for programming errors.
    • Close or release resources in finally Blocks
    • Include the cause of the exception in the stack trace.
    • Always provide meaningful and complete information about exceptions
    • Avoid excessive use of Check type exceptions
    • Convert a checkpoint exception to an exception during running
    • Remember, exceptions are expensive for performance.
    • Avoid empty catch Blocks
    • Usage standard exception
    • Record exceptions thrown by any method
    • Differences between checked exceptions and runtime exceptions:
      • The checked exceptions need to be handled by yourself, and the runtime exceptions do not need to be
      • The checked Exception is the direct subclass of Exception, and the runtime Exception is the subclass of RuntimeException.
      • Most of the checked exceptions are errors during programming, and the failure rate during running is high.
      • Best practices for avoiding NullPointerException [5]:
        • Call the equals () and equalsIgnoreCase () methods ["hello". equals (objString)] with known string objects )];
        • If the return values of the valueOf () and toString () methods are the same, use the valueOf () method instead of the toString () method [when the null object calls toString () an NullPointerException exception is thrown when the method is called. When the valueOf () method is called, a "null" encapsulation class is returned ];
        • Use null-safe methods and libraries such as eg, StringUtils. isBlank (), isNumeric (), and isWhiteSpace ];
        • The return value of a method call should return an empty set or an empty array to avoid the return of null [Collections. EMPTY_LIST, Collections. EMPTY_SET and Collections. EMPTY_MAP ];
        • The @ NotNull and @ Nullable annotations are used to indicate whether null may occur;
        • Avoid unnecessary automatic packing and unpacking in the code. [avoid receiving a return value of null for int a. Use Integer a instead of null ];
        • Follow the contract and use a reasonable default value [the caller can make a clear decision by defining what can be blank and what cannot be blank .];
        • When using a database to store objects, You need to define whether to allow a field to be null. In this way, the database's own mechanism can check whether it is null to avoid invalid blank fields after the program calls it.
        • Use null to encapsulate the Null class of the object.

          Customize an Exception class:

          ProjectNameException. java content is as follows:

          ?

          package com.trianlge23.projectname.exception;public class ProjectNameException extends Throwable {private static final long serialVersionUID = 8093803025939797139L;//exception codeprivate int exceptionCode;//exception detailed messageprivate String detailMsg;public ProjectNameException(int exceptionCode, String extraMsg) {super();this.setDetailMsg(exceptionCode);this.setExtraMsg(extraMsg);}public ProjectNameException(int exceptionCode) {super();this.setDetailMsg(exceptionCode);}//notice: we do not offer the set method to set the excption code.public int getExceptionCode() {return exceptionCode;}//if there has no extra message for this excption code, init it.private void setDetailMsg(int exceptionCode) {this.exceptionCode = exceptionCode;if (ProjectNameExceptionCode.EXCEPTION_CODE_MAP.containsKey(exceptionCode)) {this.detailMsg = ProjectNameExceptionCode.EXCEPTION_CODE_MAP.get(exceptionCode);} else {this.detailMsg = ProjectNameExceptionCode.EXCEPTION_CODE_MAP.get(ProjectNameExceptionCode.PROJECTNAME_EXCEPTION_CODE_NOT_FOUND);}}//if there has extra message for this exception code, add it.private void setExtraMsg(String extraMsg) {this.detailMsg += ProjectNameExceptionCode.EXTRA_EXCEPTION_MSG_SPLITER+ extraMsg;}//override the super class method getMessage()@Overridepublic String getMessage() {return this.detailMsg;}}


          The content of ProjectNameExceptionCode. java is as follows:

          ?

          package com.triangle23.projectname.exception;import java.util.HashMap;import java.util.Map;public class ProjectNameExceptionCode {//the separator between default message and extra message of exception.public static final String EXTRA_EXCEPTION_MSG_SPLITER = ": ";//the map stores the exception code and exception messagepublic static Map
                   
                     EXCEPTION_CODE_MAP;public static final int PROJECTNAME_EXCEPTION_CODE_NOT_FOUND = 1;static {EXCEPTION_CODE_MAP = new HashMap
                    
                     ();EXCEPTION_CODE_MAP.put(PROJECTNAME_EXCEPTION_CODE_NOT_FOUND,"[PROJECTNAME Exception] Not found exception code.");}}
                    
                   



          References:

          1. JDK1.7 API: http://docs.oracle.com/javase/7/docs/api/

          2. Java programming ideas (version 4)

          3. Valid Java

          4. Exception Handling Java Best Practices:
          Http://javarevisited.blogspot.com/2013/03/0-exception-handling-best-practices-in-Java-Programming.html

          5. Java Tips and Best practices to avoid NullPointerException:
          Http://javarevisited.blogspot.com/2013/05/java-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html


          Note:

          If you have any mistakes, please correct them. You are welcome to discuss them and give us some guidance.

          Last Updated:


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.