欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一起聊聊Java中的自定義異常

 更新時間:2022年08月19日 16:22:45   作者:進擊的Matrix  
在學(xué)習Java的過程中,想必大家都一定學(xué)習過異常這個篇章,異常的基本特性和使用這里就不再多講了。本文就來和大家講講如何自定義異常

在學(xué)習Java的過程中,想必大家都一定學(xué)習過異常這個篇章,異常的基本特性和使用這里就不再多講了。想必大家都能夠理解看懂,并正確使用。

但是,光學(xué)會基本異常處理和使用不夠的,在工作中常會有自定義業(yè)務(wù)異常的場景,根據(jù)不同的業(yè)務(wù)異常做對應(yīng)異常處理,出現(xiàn)異常并不可怕,有時候是需要使用異常來驅(qū)動業(yè)務(wù)的處理,例如: 在使用唯一約束的數(shù)據(jù)庫的時候,如果插入一條重復(fù)的數(shù)據(jù),那么可以通過捕獲唯一約束異常DuplicateKeyException,如果出現(xiàn)CommunicationsException是不是又要去處理呢?如果兩種情況都使用同樣業(yè)務(wù)邏輯來處理,是不是同樣捕獲呢?這個時候,其實如果在DAO層統(tǒng)一捕獲Exception,然后向上拋出自定義異常,在調(diào)用成層根據(jù)對應(yīng)的業(yè)務(wù)異常再進行處理,而且自定義異常能做很多輕量化處理(請看下文解釋),是不是方便很多呢?所以這里自定義業(yè)務(wù)異常:既是對業(yè)務(wù)不同異常場景下的區(qū)分,又是通過異常來驅(qū)動業(yè)務(wù)流程的處理,以自定義異常好處很多。

Java中的異常

Java中默認的異常信息有哪些呢?Java程序中捕獲異常之后會將異常進行輸出,不知道細心的同學(xué)有沒有注意到一點,輸出的異常是什么東西呢?下面來看一個常見的ArithmeticException異常:

java.lang.ArithmeticException: / by zero
    at greenhouse.ExceptionTest.testException(ExceptionTest.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

再看看一個Java程序員耳熟能詳?shù)腘ullPointerException空指針異常:

java.lang.NullPointerException
    at greenhouse.ExceptionTest.testException(ExceptionTest.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

大家有沒有發(fā)現(xiàn)一個特點,就是異常的輸出中能夠精確的輸出異常出現(xiàn)的地點,精確到每一行代碼,還有后面一大堆的執(zhí)行過程類調(diào)用,也都打印出來了,這些信息從哪兒來呢?

這些信息是從棧中獲取的,在打印異常日志的時候,會從JVM 棧中去獲取這些調(diào)用信息。能夠精確的定位異常出現(xiàn)的異常當然是好,但是我們有時候考慮到程序的性能,以及一些需求時,我們有時候并不需要完全的打印這些信息,并且去方法調(diào)用棧中獲取相應(yīng)的信息,是有性能消耗的,對于一些性能要求高的程序,我們完全可以在異常處理方面為程序性能做一個性能提升。

自定義Java異常類

所以如何避免輸出這些堆棧信息呢? 那么自定義異常就可以解決這個問題:

首先,自定義異常需要繼承RuntimeException,然后,再通過是重寫fillInStackTrace,toString 方法,例如下面我定義一個AppException異常:

package com.green.monitor.common.exception;

import java.text.MessageFormat;
/**
 * 自定義異常類
 */
public class AppException extends RuntimeException {

	private boolean isSuccess = false;
	private String key;
	private String info;

	public AppException(String key) {
		super(key);
		this.key = key;
		this.info = key;
	}

	public AppException(String key, String message) {
		super(MessageFormat.format("{0}[{1}]", key, message));
		this.key = key;
		this.info = message;
	}

	public AppException(String message, String key, String info) {
		super(message);
		this.key = key;
		this.info = info;
	}

	public boolean isSuccess() {
		return isSuccess;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	@Override
	public Throwable fillInStackTrace() {
		return this;
	}

	@Override
	public String toString() {
		return MessageFormat.format("{0}[{1}]",this.key,this.info);
	}
}

Java異常源碼

那么為什么要重寫fillInStackTrace,和 toString 方法呢? 我們首先來看源碼是怎么一回事。

public class RuntimeException extends Exception {
    static final long serialVersionUID = -7034897190745766939L;

    /** Constructs a new runtime exception with <code>null</code> as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public RuntimeException() {
	      super();
    }

    /** Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for 
     *          later retrieval by the {@link #getMessage()} method.
     */
    public RuntimeException(String message) {
        super(message);
    }

    /**
     * Constructs a new runtime exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * <code>cause</code> is <i>not</i> automatically incorporated in
     * this runtime exception's detail message.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link #getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public RuntimeException(String message, Throwable cause) {
        super(message, cause);
    }

    /** Constructs a new runtime exception with the specified cause and a
     * detail message of <tt>(cause==null ? null : cause.toString())</tt>
     * (which typically contains the class and detail message of
     * <tt>cause</tt>).  This constructor is useful for runtime exceptions
     * that are little more than wrappers for other throwables.
     *
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public RuntimeException(Throwable cause) {
        super(cause);
    }
}

RuntimeException是繼承Exception,但是它里面只是調(diào)用了父類的方法,本身是沒有做什么其余的操作。那么繼續(xù)看Exception里面是怎么回事。

public class Exception extends Throwable {
    static final long serialVersionUID = -3387516993124229948L;

    /**
     * Constructs a new exception with <code>null</code> as its detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     */
    public Exception() {
	    super();
    }

    /**
     * Constructs a new exception with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for 
     *          later retrieval by the {@link #getMessage()} method.
     */
    public Exception(String message) {
	    super(message);
    }

    /**
     * Constructs a new exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * <code>cause</code> is <i>not</i> automatically incorporated in
     * this exception's detail message.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link #getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public Exception(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new exception with the specified cause and a detail
     * message of <tt>(cause==null ? null : cause.toString())</tt> (which
     * typically contains the class and detail message of <tt>cause</tt>).
     * This constructor is useful for exceptions that are little more than
     * wrappers for other throwables (for example, {@link
     * java.security.PrivilegedActionException}).
     *
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public Exception(Throwable cause) {
        super(cause);
    }
}

從源碼中可以看到,Exception里面也是直接調(diào)用了父類的方法,和RuntimeException一樣,自己其實并沒有做什么。那么直接來看Throwable里面是怎么一回事:

public class Throwable implements Serializable {
  public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    }
    
     /**
     * Fills in the execution stack trace. This method records within this
     * <code>Throwable</code> object information about the current state of
     * the stack frames for the current thread.
     *
     * @return  a reference to this <code>Throwable</code> instance.
     * @see     java.lang.Throwable#printStackTrace()
     */
    public synchronized native Throwable fillInStackTrace();
    
       /**
     * Provides programmatic access to the stack trace information printed by
     * {@link #printStackTrace()}.  Returns an array of stack trace elements,
     * each representing one stack frame.  The zeroth element of the array
     * (assuming the array's length is non-zero) represents the top of the
     * stack, which is the last method invocation in the sequence.  Typically,
     * this is the point at which this throwable was created and thrown.
     * The last element of the array (assuming the array's length is non-zero)
     * represents the bottom of the stack, which is the first method invocation
     * in the sequence.
     *
     * <p>Some virtual machines may, under some circumstances, omit one
     * or more stack frames from the stack trace.  In the extreme case,
     * a virtual machine that has no stack trace information concerning
     * this throwable is permitted to return a zero-length array from this
     * method.  Generally speaking, the array returned by this method will
     * contain one element for every frame that would be printed by
     * <tt>printStackTrace</tt>.
     *
     * @return an array of stack trace elements representing the stack trace
     *         pertaining to this throwable.
     * @since  1.4
     */
    public StackTraceElement[] getStackTrace() {
        return (StackTraceElement[]) getOurStackTrace().clone();
    }

    private synchronized StackTraceElement[] getOurStackTrace() {
        // Initialize stack trace if this is the first call to this method
        if (stackTrace == null) {
            int depth = getStackTraceDepth();
            stackTrace = new StackTraceElement[depth];
            for (int i=0; i < depth; i++)
                stackTrace[i] = getStackTraceElement(i);
        }
        return stackTrace;
    }
    
    /**
     * Returns the number of elements in the stack trace (or 0 if the stack
     * trace is unavailable).
     *
     * package-protection for use by SharedSecrets.
     */
    native int getStackTraceDepth();

    /**
     * Returns the specified element of the stack trace.
     *
     * package-protection for use by SharedSecrets.
     *
     * @param index index of the element to return.
     * @throws IndexOutOfBoundsException if <tt>index &lt; 0 ||
     *         index &gt;= getStackTraceDepth() </tt>
     */
    native StackTraceElement getStackTraceElement(int index);
    
    /**
     * Returns a short description of this throwable.
     * The result is the concatenation of:
     * <ul>
     * <li> the {@linkplain Class#getName() name} of the class of this object
     * <li> ": " (a colon and a space)
     * <li> the result of invoking this object's {@link #getLocalizedMessage}
     *      method
     * </ul>
     * If <tt>getLocalizedMessage</tt> returns <tt>null</tt>, then just
     * the class name is returned.
     *
     * @return a string representation of this throwable.
     */
    public String toString() {
        String s = getClass().getName();
        String message = getLocalizedMessage();
        return (message != null) ? (s + ": " + message) : s;
    }

從源碼中可以看到,到Throwable就幾乎到頭了,在fillInStackTrace() 方法是一個native方法,這方法也就是會調(diào)用底層的C語言,返回一個Throwable對象,toString 方法,返回的是throwable的簡短描述信息,并且在getStackTrace 方法和 getOurStackTrace 中調(diào)用的都是native方法getStackTraceElement,而這個方法是返回指定的棧元素信息,所以這個過程肯定是消耗性能的,那么我們自定義異常中的重寫toString方法和fillInStackTrace方法就可以不從棧中去獲取異常信息,直接輸出,這樣對系統(tǒng)和程序來說,相對就沒有那么"重",是一個優(yōu)化性能的非常好的辦法。

按照上面我們舉例的自定義AppException異常,如果出現(xiàn)異常了,這個AppException異常輸出是什么樣的信息呢?請看下面吧:

@Test
    public void testException(){
        try {
            String str =null;
            System.out.println(str.charAt(0));
        }catch (Exception e){
            throw new AppException("000001","空指針異常");
        }
    }

執(zhí)行上面單元測試,在異常異常的時候,系統(tǒng)將會打印我們自定義的異常信息:

000001[空指針異常]

Process finished with exit code -1

所以特別簡潔,優(yōu)化了系統(tǒng)程序性能,讓程序不這么“重”,所以對于性能要求特別要求的系統(tǒng),趕緊自定義業(yè)務(wù)異常試一試吧!

到此這篇關(guān)于一起聊聊Java中的自定義異常的文章就介紹到這了,更多相關(guān)Java自定義異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MyBatisPlus批量添加的優(yōu)化與報錯解決

    MyBatisPlus批量添加的優(yōu)化與報錯解決

    MybatisPlus是一個高效的java持久層框架,它在Mybatis的基礎(chǔ)上增加了一些便捷的功能,提供了更加易用的API,可以大幅度提高開發(fā)效率,這篇文章主要給大家介紹了關(guān)于MyBatisPlus批量添加的優(yōu)化與報錯解決的相關(guān)資料,需要的朋友可以參考下
    2023-05-05
  • Java花式解決'分割回文串 ii'問題詳解

    Java花式解決'分割回文串 ii'問題詳解

    最學(xué)習動態(tài)規(guī)劃思想的路上,遇見了‘分割回文串問題’,如臨大敵啊,題目聽起來蠻簡單,思考起來卻也沒那么容易,本文將為大家詳細介紹幾種解決分割回文串 ii問題的辦法,需要的可以參考一下
    2021-12-12
  • 詳談Spring框架之事務(wù)管理

    詳談Spring框架之事務(wù)管理

    下面小編就為大家?guī)硪黄斦凷pring框架之事務(wù)管理。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • 使用maven開發(fā)springboot項目時pom.xml常用配置(推薦)

    使用maven開發(fā)springboot項目時pom.xml常用配置(推薦)

    這篇文章主要介紹了使用maven開發(fā)springboot項目時的pom.xml常用配置,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • java RocketMQ快速入門基礎(chǔ)知識

    java RocketMQ快速入門基礎(chǔ)知識

    這篇文章主要介紹了java RocketMQ快速入門基礎(chǔ)知識,所以RocketMQ是站在巨人的肩膀上(kafka),又對其進行了優(yōu)化讓其更滿足互聯(lián)網(wǎng)公司的特點。它是純Java開發(fā),具有高吞吐量、高可用性、適合大規(guī)模分布式系統(tǒng)應(yīng)用的特點。,需要的朋友可以參考下
    2019-06-06
  • Java中HashMap與String字符串互轉(zhuǎn)的問題解決

    Java中HashMap與String字符串互轉(zhuǎn)的問題解決

    本文介紹了Java中HashMap與String字符串互轉(zhuǎn)的問題解決,當我們有需求將HashMap轉(zhuǎn)為Json格式的String時,需要使用FastJson/Gson將HashMap轉(zhuǎn)為String,感興趣的可以了解一下
    2022-03-03
  • Java中的CompletableFuture使用解析

    Java中的CompletableFuture使用解析

    這篇文章主要介紹了Java中的CompletableFuture使用解析,為什么CompletableFuture要定制化線程池,因為默認的線程池是ForkJoinPool,這個線程池的最大線程數(shù)默認是你的電腦的線程數(shù)數(shù)減1,假如我線程電腦是4核8線程的,ForkJoinPool的最大線程數(shù)就是7,需要的朋友可以參考下
    2024-01-01
  • Java實現(xiàn)數(shù)據(jù)庫連接池的方法

    Java實現(xiàn)數(shù)據(jù)庫連接池的方法

    這篇文章主要介紹了Java實現(xiàn)數(shù)據(jù)庫連接池的方法,涉及java數(shù)據(jù)庫連接池的創(chuàng)建、連接、刷新、關(guān)閉及狀態(tài)獲取的常用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • 淺談Spring中的循環(huán)依賴問題與解決方案

    淺談Spring中的循環(huán)依賴問題與解決方案

    這篇文章主要介紹了淺談Spring中的循環(huán)依賴問題與解決方案,循環(huán)依賴就是兩個或則兩個以上的bean互相持有對方,最終形成閉環(huán),比如A依賴于B,B依賴于C,C又依賴于A,需要的朋友可以參考下
    2023-12-12
  • Java中的cglib原理解析

    Java中的cglib原理解析

    這篇文章主要介紹了Java中的cglib原理解析,由于代理類繼承了被代理類,所以調(diào)用sayHello()方法時會直接調(diào)用代理類的sayHello()方法,而在代理類的方法中,調(diào)用了Callback的邏輯,需要的朋友可以參考下
    2023-10-10

最新評論