一起聊聊Java中的自定义异常

 更新时间:2022年08月19日 16:22:45   作者:进击的Matrix  
在学习Java的过程中,想必大家都一定学习过异常这个篇章,异常的基本特性和使用这里就不再多讲了。本文就来和大家讲讲如何自定义异常

在学习Java的过程中,想必大家都一定学习过异常这个篇章,异常的基本特性和使用这里就不再多讲了。想必大家都能够理解看懂,并正确使用。

但是,光学会基本异常处理和使用不够的,在工作中常会有自定义业务异常的场景,根据不同的业务异常做对应异常处理,出现异常并不可怕,有时候是需要使用异常来驱动业务的处理,例如: 在使用唯一约束的数据库的时候,如果插入一条重复的数据,那么可以通过捕获唯一约束异常DuplicateKeyException,如果出现CommunicationsException是不是又要去处理呢?如果两种情况都使用同样业务逻辑来处理,是不是同样捕获呢?这个时候,其实如果在DAO层统一捕获Exception,然后向上抛出自定义异常,在调用成层根据对应的业务异常再进行处理,而且自定义异常能做很多轻量化处理(请看下文解释),是不是方便很多呢?所以这里自定义业务异常:既是对业务不同异常场景下的区分,又是通过异常来驱动业务流程的处理,以自定义异常好处很多。

Java中的异常

Java中默认的异常信息有哪些呢?Java程序中捕获异常之后会将异常进行输出,不知道细心的同学有没有注意到一点,输出的异常是什么东西呢?下面来看一个常见的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程序员耳熟能详的NullPointerException空指针异常:

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)

大家有没有发现一个特点,就是异常的输出中能够精确的输出异常出现的地点,精确到每一行代码,还有后面一大堆的执行过程类调用,也都打印出来了,这些信息从哪儿来呢?

这些信息是从栈中获取的,在打印异常日志的时候,会从JVM 栈中去获取这些调用信息。能够精确的定位异常出现的异常当然是好,但是我们有时候考虑到程序的性能,以及一些需求时,我们有时候并不需要完全的打印这些信息,并且去方法调用栈中获取相应的信息,是有性能消耗的,对于一些性能要求高的程序,我们完全可以在异常处理方面为程序性能做一个性能提升。

自定义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,但是它里面只是调用了父类的方法,本身是没有做什么其余的操作。那么继续看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里面也是直接调用了父类的方法,和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方法,这方法也就是会调用底层的C语言,返回一个Throwable对象,toString 方法,返回的是throwable的简短描述信息,并且在getStackTrace 方法和 getOurStackTrace 中调用的都是native方法getStackTraceElement,而这个方法是返回指定的栈元素信息,所以这个过程肯定是消耗性能的,那么我们自定义异常中的重写toString方法和fillInStackTrace方法就可以不从栈中去获取异常信息,直接输出,这样对系统和程序来说,相对就没有那么"重",是一个优化性能的非常好的办法。

按照上面我们举例的自定义AppException异常,如果出现异常了,这个AppException异常输出是什么样的信息呢?请看下面吧:

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

执行上面单元测试,在异常异常的时候,系统将会打印我们自定义的异常信息:

000001[空指针异常]

Process finished with exit code -1

所以特别简洁,优化了系统程序性能,让程序不这么“重”,所以对于性能要求特别要求的系统,赶紧自定义业务异常试一试吧!

到此这篇关于一起聊聊Java中的自定义异常的文章就介绍到这了,更多相关Java自定义异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • MyBatisPlus批量添加的优化与报错解决

    MyBatisPlus批量添加的优化与报错解决

    MybatisPlus是一个高效的java持久层框架,它在Mybatis的基础上增加了一些便捷的功能,提供了更加易用的API,可以大幅度提高开发效率,这篇文章主要给大家介绍了关于MyBatisPlus批量添加的优化与报错解决的相关资料,需要的朋友可以参考下
    2023-05-05
  • Java花式解决'分割回文串 ii'问题详解

    Java花式解决'分割回文串 ii'问题详解

    最学习动态规划思想的路上,遇见了‘分割回文串问题’,如临大敌啊,题目听起来蛮简单,思考起来却也没那么容易,本文将为大家详细介绍几种解决分割回文串 ii问题的办法,需要的可以参考一下
    2021-12-12
  • 详谈Spring框架之事务管理

    详谈Spring框架之事务管理

    下面小编就为大家带来一篇详谈Spring框架之事务管理。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • 使用maven开发springboot项目时pom.xml常用配置(推荐)

    使用maven开发springboot项目时pom.xml常用配置(推荐)

    这篇文章主要介绍了使用maven开发springboot项目时的pom.xml常用配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • java RocketMQ快速入门基础知识

    java RocketMQ快速入门基础知识

    这篇文章主要介绍了java RocketMQ快速入门基础知识,所以RocketMQ是站在巨人的肩膀上(kafka),又对其进行了优化让其更满足互联网公司的特点。它是纯Java开发,具有高吞吐量、高可用性、适合大规模分布式系统应用的特点。,需要的朋友可以参考下
    2019-06-06
  • Java中HashMap与String字符串互转的问题解决

    Java中HashMap与String字符串互转的问题解决

    本文介绍了Java中HashMap与String字符串互转的问题解决,当我们有需求将HashMap转为Json格式的String时,需要使用FastJson/Gson将HashMap转为String,感兴趣的可以了解一下
    2022-03-03
  • Java中的CompletableFuture使用解析

    Java中的CompletableFuture使用解析

    这篇文章主要介绍了Java中的CompletableFuture使用解析,为什么CompletableFuture要定制化线程池,因为默认的线程池是ForkJoinPool,这个线程池的最大线程数默认是你的电脑的线程数数减1,假如我线程电脑是4核8线程的,ForkJoinPool的最大线程数就是7,需要的朋友可以参考下
    2024-01-01
  • Java实现数据库连接池的方法

    Java实现数据库连接池的方法

    这篇文章主要介绍了Java实现数据库连接池的方法,涉及java数据库连接池的创建、连接、刷新、关闭及状态获取的常用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • 浅谈Spring中的循环依赖问题与解决方案

    浅谈Spring中的循环依赖问题与解决方案

    这篇文章主要介绍了浅谈Spring中的循环依赖问题与解决方案,循环依赖就是两个或则两个以上的bean互相持有对方,最终形成闭环,比如A依赖于B,B依赖于C,C又依赖于A,需要的朋友可以参考下
    2023-12-12
  • Java中的cglib原理解析

    Java中的cglib原理解析

    这篇文章主要介绍了Java中的cglib原理解析,由于代理类继承了被代理类,所以调用sayHello()方法时会直接调用代理类的sayHello()方法,而在代理类的方法中,调用了Callback的逻辑,需要的朋友可以参考下
    2023-10-10

最新评论