新聞中心
前言
專注于為中小企業(yè)提供成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)江南免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了成百上千企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過(guò)網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
在學(xué)習(xí)Java的過(guò)程中,想必大家都一定學(xué)習(xí)過(guò)異常這個(gè)篇章,異常的基本特性和使用這里就不再多講了。什么是異常?我不知道大家都是怎么去理解的,我的理解很簡(jiǎn)單,那就是不正常的情況,比如我現(xiàn)在是個(gè)男的,但是我卻有著女人所獨(dú)有的東西,在我看來(lái)這尼瑪肯定是種異常,簡(jiǎn)直不能忍。想必大家都能夠理解看懂,并正確使用。
但是,光學(xué)會(huì)基本異常處理和使用不夠的,在工作中出現(xiàn)異常并不可怕,有時(shí)候是需要使用異常來(lái)驅(qū)動(dòng)業(yè)務(wù)的處理,例如: 在使用唯一約束的數(shù)據(jù)庫(kù)的時(shí)候,如果插入一條重復(fù)的數(shù)據(jù),那么可以通過(guò)捕獲唯一約束異常DuplicateKeyException來(lái)進(jìn)行處理,這個(gè)時(shí)候,在server層中就可以向調(diào)用層拋出對(duì)應(yīng)的狀態(tài),上層根據(jù)對(duì)應(yīng)的狀態(tài)再進(jìn)行處理,所以有時(shí)候異常對(duì)業(yè)務(wù)來(lái)說(shuō),是一個(gè)驅(qū)動(dòng)方式。
有的捕獲異常之后會(huì)將異常進(jìn)行輸出,不知道細(xì)心的同學(xué)有沒(méi)有注意到一點(diǎn),輸出的異常是什么東西呢?
下面來(lái)看一個(gè)常見(jiàn)的異常:
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)
一個(gè)空指針異常:
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)
大家有沒(méi)有發(fā)現(xiàn)一個(gè)特點(diǎn),就是異常的輸出是中能夠精確的輸出異常出現(xiàn)的地點(diǎn),還有后面一大堆的執(zhí)行過(guò)程類調(diào)用,也都打印出來(lái)了,這些信息從哪兒來(lái)呢? 這些信息是從棧中獲取的,在打印異常日志的時(shí)候,會(huì)從棧中去獲取這些調(diào)用信息。能夠精確的定位異常出現(xiàn)的異常當(dāng)然是好,但是我們有時(shí)候考慮到程序的性能,以及一些需求時(shí),我們有時(shí)候并不需要完全的打印這些信息,并且去方法調(diào)用棧中獲取相應(yīng)的信息,是有性能消耗的,對(duì)于一些性能要求高的程序,我們完全可以在這一個(gè)方面為程序性能做一個(gè)提升。
所以如何避免輸出這些堆棧信息呢? 那么自定義異常就可以解決這個(gè)問(wèn)題:
首先,自動(dòng)異常需要繼承RuntimeException, 然后,再通過(guò)是重寫fillInStackTrace, toString 方法, 例如,下面我定義一個(gè)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); } }
那么為什么要重寫fillInStackTrace, 和 toString 方法呢? 我們首先來(lái)看源碼是怎么一回事.
public class RuntimeException extends Exception { static final long serialVersionUID = -7034897190745766939L; /** Constructs a new runtime exception withnull
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.Note that the detail message associated with *
cause
is not 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 null 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 (cause==null ? null : cause.toString()) * (which typically contains the class and detail message of * cause). 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 null 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)用了父類的方法,本身是沒(méi)有做什么其余的操作。那么繼續(xù)看Exception里面是怎么回事呢?
public class Exception extends Throwable { static final long serialVersionUID = -3387516993124229948L; /** * Constructs a new exception withnull
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.Note that the detail message associated with *
cause
is not 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 null 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 (cause==null ? null : cause.toString()) (which * typically contains the class and detail message of cause). * 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 null 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一樣,自己其實(shí)并沒(méi)有做什么。 那么直接來(lái)看Throwable里面是怎么一回事:
public class Throwable implements Serializable { public Throwable(String message) { fillInStackTrace(); detailMessage = message; } /** * Fills in the execution stack trace. This method records within this *Throwable
object information about the current state of * the stack frames for the current thread. * * @return a reference to thisThrowable
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. * *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 * printStackTrace. * * @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 index < 0 || * index >= getStackTraceDepth() */ native StackTraceElement getStackTraceElement(int index); /** * Returns a short description of this throwable. * The result is the concatenation of: *
-
*
- the {@linkplain Class#getName() name} of the class of this object *
- ": " (a colon and a space) *
- the result of invoking this object's {@link #getLocalizedMessage} * method *
從源碼中可以看到,到Throwable就幾乎到頭了, 在fillInStackTrace() 方法是一個(gè)native方法,這方法也就是會(huì)調(diào)用底層的C語(yǔ)言,返回一個(gè)Throwable對(duì)象, toString 方法,返回的是throwable的簡(jiǎn)短描述信息, 并且在getStackTrace 方法和 getOurStackTrace 中調(diào)用的都是native方法getStackTraceElement, 而這個(gè)方法是返回指定的棧元素信息,所以這個(gè)過(guò)程肯定是消耗性能的,那么我們自定義異常中的重寫toString方法和fillInStackTrace方法就可以不從棧中去獲取異常信息,直接輸出,這樣對(duì)系統(tǒng)和程序來(lái)說(shuō),相對(duì)就沒(méi)有那么”重”, 是一個(gè)優(yōu)化性能的非常好的辦法。那么如果出現(xiàn)自定義異常那么是什么樣的呢?請(qǐng)看下面吧:
@Test public void testException(){ try { String str =null; System.out.println(str.charAt(0)); }catch (Exception e){ throw new AppException("000001","空指針異常"); } }
那么在異常異常的時(shí)候,系統(tǒng)將會(huì)打印我們自定義的異常信息:
000001[空指針異常] Process finished with exit code -1
所以特別簡(jiǎn)潔,優(yōu)化了系統(tǒng)程序性能,讓程序不這么“重”, 所以對(duì)于性能要求特別要求的系統(tǒng)。趕緊自己的自定義異常吧!
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)創(chuàng)新互聯(lián)的支持。
當(dāng)前名稱:Java如何自定義異常打印非堆棧信息詳解
標(biāo)題來(lái)源:http://fisionsoft.com.cn/article/jghogc.html