Java custom exceptions and exceptions use best practices

Source: Internet
Author: User
Tags stack trace throwable

Classification of exceptions
1. Non-runtime exception (Checked Exception)
All classes in Java that inherit from exception but not inherit from RuntimeException are non-runtime exceptions.
2. Runtime exception (runtime exception/unchecked Exception)
The RuntimeException class inherits directly from the exception class, called a run-time exception. All run-time exceptions in Java are inherited directly or indirectly from RuntimeException.
All exception classes in Java are inherited directly or indirectly from exception.
Handling of exceptions
First, the corresponding non-runtime exception, it must be processed. There are two ways of handling this:
-Capture using the try...catch...finally statement block
-method declaration of the method where the exception was generated throws Exception
Second, for the run-time exception, it can not be processed, it can also be processed. In general, it is not processed.
There are exceptions when using the Java API approach, and we need to create and use custom exceptions due to the actual need. Use the new Exception class to apply to the System program.
When it comes to custom exceptions, the first thing to talk about is the benefits of using custom exceptions and using custom exceptions. Custom exceptions are created to represent some of the error types of your application, to provide a new meaning for one or more of the problems that might occur in your code, to show the similarities of errors between multiple locations of your code, to distinguish one or more errors that may occur when the code is running, or to give special meaning to a set of errors in your application.
Application Scenarios
The basic role of the server is to handle communication with the client, and if you use standard Java APIs (such as classes in Java.io and java.net packages) to write the server, you can make the code that you write throw IOException in multiple places. When you set up a server, wait for a client to connect, and get traffic, IOException can be thrown, and IOException are thrown during communication and when attempting to disconnect. In short, the various parts of the server are throwing IOException.
This ioexception meaning is different for a server. Although represented by the same exception type, there is a difference in the business meaning of each exception, and the reporting and recovery operations are not the same. Therefore, you can associate an exception set with a server configuration and startup problem, associate another exception set with the actual action of client communication, and associate a third exception set with the server shutdown task. With custom exceptions, you can express errors flexibly in ways that make sense to your application.
To do this, we need to use a custom exception to fix the problem, positioning the problem with the exact location of the exception.
custom Exception class procedures
1. In most cases, you simply inherit the exception class exception, and you often need to define one or more constructors to store the error message in the object.
Extensions:
-Class java.lang.Throwable is the base class for all exception classes and includes two subclasses: the exception and Error,exception classes are used to describe exceptions that the program can catch, such as classnotfoundexception. The error class is used to indicate that a reasonable application should not attempt to capture a serious problem, such as a virtual machine error virtualmachineerror
-Custom exception classes can inherit the Throwable class or the exception class instead of inheriting the error class. You can also have an inheritance relationship between custom exception classes
-You need to design a construction method for your custom exception class to make it easier to construct custom exception objects.
Some of the standard features of the Throwable class are automatically inherited when any exception is inherited, such as:
-Error message
-Stack Tracking
-Abnormal packaging

To add additional information to the exception, you can add some variables and methods to the class. The custom exception shown in this example is not named after the business type, but instead creates a generic exception class that RETCD to distinguish between the business type and where the exception occurred, and of course the specific RETCD value must be specified beforehand or explained.

/** * In most cases, creating a custom exception requires inheriting exception, which inherits exception subclasses RuntimeException * @author MAHC * */public class Customerexception Extends RuntimeException {private String retcd;  The return code of the exception corresponds to the private String msgdes;  The description information for the exception corresponds to public customerexception () {super ();} Public customerexception (String message) {super (message); msgdes = message;} Public Customerexception (String Retcd, String msgdes) {super (); This.retcd = Retcd;this.msgdes = Msgdes;} Public String Getretcd () {return RETCD;} Public String Getmsgdes () {return msgdes;}}

2. Declaring a method throws a custom exception. In order to use a custom exception, you must inform the calling code of the class: Prepare to handle this exception type. To do this, declare one or more methods to throw an exception. Find the point where the exception occurred, create a new exception, and add the keyword throw.

public class TestClass {public void TestException () throws Customerexception {try {<p>//. Some code that throws <span style= "Font-family:simsun;" >customerexception</span></p>} catch (Exception e) {throw new Customerexception ("14000001", "string[" STRs ' s length < 4 ");}}}

3. Customize the exception test action.

public class Testcustomerexception {public static void main (string[] args) {try {TestClass TestClass = new TestClass (); TES Tclass.testexception ();} catch (Customerexception e) {e.printstacktrace (); System.out.println ("Msgdes\t" +e.getmsgdes ()); System.out.println ("Retcd\t" +E.GETRETCD ());}}}
The following best practices for custom exceptions, taken from the network, are used by reference extensions.
Best practices for using exceptions
The following section lists some of the best implementations of the client-side code handling API throwing exceptions.
1. Remember to release resources
If you are using a database or network-attached resource, remember to release them. If you use APIs that use only unchecked exception, you should release them when you're done using try-final.
public void Dataaccesscode () {    Connection conn = null;    try{        conn = getconnection ();        Some code that throws SQLException    }catch (SQLException ex) {        ex.printstacktrace ();    } finally{        Dbutil.closeconnection (conn);    }} Class dbutil{public    static void CloseConnection        (Connection conn) {        try{            conn.close ();        } catch (SQLException ex) {            logger.error ("Cannot close connection");            throw new RuntimeException (ex);}}    

Dbutil is a tool class that closes a connection. The most important part is the finally, which executes regardless of whether an exception occurs. In this example, finally closes the connection and throws a runtimeexception if a problem occurs during the shutdown process.
2. Do not use exceptions for the control process
Generating stack backtracking is very expensive, and the value of stack backtracking lies in debugging. In Process control, stack backtracking should be avoided because the client simply wants to know how to proceed.
The following code, a custom exception maximumcountreachedexception, is used to control the flow.

public void Useexceptionsforflowcontrol () {    try {        while (true) {            increasecount ();        }    } catch ( Maximumcountreachedexception ex) {    }    //continue execution} public void Increasecount ()    throws maximumcountreachedexception {    if (count >=)        throw new Maximumcountreachedexception ();}

Useexceptionsforflowcontrol () uses an infinite loop to increment the counter until the exception is thrown. This writing not only reduces the readability of the code, it also makes the code slow. Remember that exceptions are only used in cases where an exception occurs.
3. Do not ignore exceptions
When an API method throws checked exception, it is trying to tell you that you need to take certain actions to deal with it. If it doesn't mean anything to you, don't hesitate to switch directly to unchecked exception throw, never just empty {}catch it, and then ignore it when nothing happens.
4. Do not catch the highest level of exception
Unchecked exception is inherited from the RuntimeException class, and RuntimeException inherits from exception. If catch Exception, you will catch runtimeexception.

try{..} catch (Exception ex) {}

The above code ignores unchecked exception.
5. Record only exception once
Multiple records of the same wrong stack trace can make the programmer confused about the original source of the error. So just record once is enough.
   Summary: Here are some of the best practices for exception handling that I've summed up. I do not want to provoke a heated debate about checked exception and unchecked exception. You can design the code according to your needs. I believe that as time goes by, we will find some better ways to deal with the anomalies.


"Reproduced use, please specify the source:http://blog.csdn.net/mahoking"

"Reproduced use, please specify the source:http://blog.csdn.net/mahoking"

Java custom exceptions and exceptions use best practices

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.