当前位置:

首页 > 编程开发 > Java中的自定义异常怎么实现

Java中的自定义异常怎么实现

Java中的异常Java中默认的异常信息有哪些呢?Java程序中捕获异常之后会将异常进行输出,不知道细心的同学有没有注意到一点,输出的异常是什么东西呢?下面来看一个常见的ArithmeticException异常:java.lang.ArithmeticException:/byzeroatgreenhouse.ExceptionTest.testException(ExceptionTest.java:16)atsun.reflect.NativeMethodAccessorImpl.invoke0(N

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 null 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,但是它里面只是调用了父类的方法,本身是没有做什么其余的操作。那么继续看Exception里面是怎么回事。

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

    /**
     * Constructs a new exception with null 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里面也是直接调用了父类的方法,和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
     * Throwable object information about the current state of
     * the stack frames for the current thread.
     *
     * @return  a reference to this Throwable 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      * 
     * If getLocalizedMessage returns null, 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

本文内容来源于互联网,如有侵权请联系删除。
作者最新文章
编程开发
相关文章 更多
C++动态数组初始化怎么写?常用语句与代码示例
C++动态数组初始化怎么写?常用语句与代码示例

深入解析C++中动态数组的初始化机制,涵盖new操作符的不同用法、基本类型与类对象的初始化差异,以及为何在现代C++开发中应优先使用std::vector。

谷歌浏览器Mac版入口
谷歌浏览器Mac版入口

谷歌浏览器Mac版官方安装指南 谷歌浏览器Mac版官方安装入口是https://www.google.com/chrome/,需macOS 12+系统、500MB空间,下载.dmg后拖入应用程序安装,支持多设备同步、性能优化与隐私保护功能。 苹果电脑Chrome的安装入口究竟在哪里?这个问题最近可是

Chrome浏览器JS脚本不运行怎么办
Chrome浏览器JS脚本不运行怎么办

Chrome中JavaScript未执行需依次检查:一、移除站点级禁用并添加允许域名;二、开启全局JavaScript开关;三、禁用干扰扩展;四、在开发者工具中启用JavaScript;五、重置内容设置为默认。 有时在Chrome里打开网页,会发现交互按钮点了没反应,数据加载不出来,页面仿佛“静止”

IE浏览器怀旧版在线网址
IE浏览器怀旧版在线网址

IE浏览器怀旧版在线网址:一次精准的技术时光回溯 最近,不少老用户和怀旧爱好者在反复搜索一个问题:那个经典的Internet Explorer,如今还能在哪里原汁原味地体验到?答案指向一个特定的地址:https://ie.microsoft.com/legacy/。 这个网站远不止是一个简单的“皮肤

火狐浏览器有哪些设置功能
火狐浏览器有哪些设置功能

火狐浏览器五大核心设置功能:解锁高效、安全与个性化体验 火狐浏览器功能强大,但如果不仔细挖掘,很多能大幅提升效率和安全性的设置可能就“藏着掖着”了。这就好比拥有一台高性能设备,却只用了基础模式。那么,如何把它调整到最顺手、最安全的状态?接下来,我们就聚焦于当前版本(截至2025年末)最关键的五大设置

chrome搜索免验证入口
chrome搜索免验证入口

Chrome官方免验证入口为https://www.google.cn/chrome/,提供全平台安装包、免登录即用、本地化安全机制及引擎级性能优化。 到底该去哪里找正版、免费且无需繁琐验证的Chrome浏览器入口?这个问题困扰了不少网友。今天,我们就来直通核心,为大家详细拆解Chrome引擎的官方

java heap space 选型思路:使用场景与区别整理
java heap space 选型思路:使用场景与区别整理

Java堆是JVM存储对象的核心内存区域,配置需结合场景:单体应用适中设置;大数据处理需大堆并关注GC停顿;微服务强调快速启动;高并发需精细划分堆区域。关键参数-Xms和-Xmx建议等值以稳定性能。垃圾回收器选择影响效率,如G1适用于大堆,ZGC可实现低停顿。内存错误时需监控堆状态。

java heap space 使用中遇到的问题怎么解决
java heap space 使用中遇到的问题怎么解决

Java堆内存溢出错误通常因内存泄漏、数据处理需求过大或JVM参数配置不当引起。排查时可借助jmap、堆转储及MAT等工具定位问题。解决方案包括调整JVM内存参数(如-Xmx)、修复代码中的内存泄漏、优化大数据处理逻辑,并建立持续监控与预防机制,以保障应用稳定运行。

java xml 选型思路:使用场景与区别整理
java xml 选型思路:使用场景与区别整理

XML在Java开发中用于配置、数据交换等场景。解析方式主要有DOM、SAX、StAX及第三方库。DOM适合操作小文件,SAX/StAX适合处理大文件流,JAXB用于对象与XML映射。选型需结合数据大小、内存、性能及团队熟悉度,现代框架常封装底层解析。

using namespace 使用中遇到的问题怎么解决
using namespace 使用中遇到的问题怎么解决

命名空间的基本概念与常见引入问题在C++等编程语言中,命名空间(namespace)是一种将代码标识符(如变量、函数、类名)封装在特定名称下的机制,其主要目的是避免命名冲突,尤其是在大型项目或使用多个第三方库时。使用“using namespace”指令可以将指定命名空间中的所有名称引入当前作用域,

查看更多
精品专题 更多
装机必备
装机必备

正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

Windows
Windows

正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

macOS软件
macOS软件

正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

Mac软件 更多
灵活计算器
灵活计算器
macOS/iOS/Android

灵活计算器是一款笔记式算数应用,支持实时计算、动态关联和云端同步功能。记录、整理和输出之间的过渡会更自然,适合长期写作、做笔记或持续沉淀个人内容。

赤友清理大师
赤友清理大师
macOS

赤友清理大师是一款为 Mac 设计的智能清理优化工具,可精准扫描垃圾、大文件、重复文件等,释放磁盘空间。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

WINDOWS 更多
Windows 10
Windows 10
Windows

Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

密码键盘
密码键盘
Windows/macOS/iOS/Android

密码键盘是一款兼具安全性与便捷性的高效密码管理器。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。