热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java如何自定义异常打印非堆栈信息详解

这篇文章主要给大家介绍了关于Java如何自定义异常打印非堆栈信息的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

前言

在学习Java的过程中,想必大家都一定学习过异常这个篇章,异常的基本特性和使用这里就不再多讲了。什么是异常?我不知道大家都是怎么去理解的,我的理解很简单,那就是不正常的情况,比如我现在是个男的,但是我却有着女人所独有的东西,在我看来这尼玛肯定是种异常,简直不能忍。想必大家都能够理解看懂,并正确使用。

但是,光学会基本异常处理和使用不够的,在工作中出现异常并不可怕,有时候是需要使用异常来驱动业务的处理,例如: 在使用唯一约束的数据库的时候,如果插入一条重复的数据,那么可以通过捕获唯一约束异常DuplicateKeyException来进行处理,这个时候,在server层中就可以向调用层抛出对应的状态,上层根据对应的状态再进行处理,所以有时候异常对业务来说,是一个驱动方式。

有的捕获异常之后会将异常进行输出,不知道细心的同学有没有注意到一点,输出的异常是什么东西呢?

下面来看一个常见的异常:

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.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)

大家有没有发现一个特点,就是异常的输出是中能够精确的输出异常出现的地点,还有后面一大堆的执行过程类调用,也都打印出来了,这些信息从哪儿来呢? 这些信息是从栈中获取的,在打印异常日志的时候,会从栈中去获取这些调用信息。能够精确的定位异常出现的异常当然是好,但是我们有时候考虑到程序的性能,以及一些需求时,我们有时候并不需要完全的打印这些信息,并且去方法调用栈中获取相应的信息,是有性能消耗的,对于一些性能要求高的程序,我们完全可以在这一个方面为程序性能做一个提升。

所以如何避免输出这些堆栈信息呢? 那么自定义异常就可以解决这个问题:

首先,自动异常需要继承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);
 }
}

那么为什么要重写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 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) &#63; (s + ": " + message) : s; }

从源码中可以看到,到Throwable就几乎到头了, 在fillInStackTrace() 方法是一个native方法,这方法也就是会调用底层的C语言,返回一个Throwable对象, toString 方法,返回的是throwable的简短描述信息, 并且在getStackTrace 方法和 getOurStackTrace 中调用的都是native方法getStackTraceElement, 而这个方法是返回指定的栈元素信息,所以这个过程肯定是消耗性能的,那么我们自定义异常中的重写toString方法和fillInStackTrace方法就可以不从栈中去获取异常信息,直接输出,这样对系统和程序来说,相对就没有那么”重”, 是一个优化性能的非常好的办法。那么如果出现自定义异常那么是什么样的呢?请看下面吧:

@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

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。


推荐阅读
  • 这篇文章主要介绍了Python拼接字符串的七种方式,包括使用%、format()、join()、f-string等方法。每种方法都有其特点和限制,通过本文的介绍可以帮助读者更好地理解和运用字符串拼接的技巧。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
  • C语言判断正整数能否被整除的程序
    本文介绍了使用C语言编写的判断正整数能否被整除的程序,包括输入一个三位正整数,判断是否能被3整除且至少包含数字3的方法。同时还介绍了使用qsort函数进行快速排序的算法。 ... [详细]
  • 本文介绍了使用Python解析C语言结构体的方法,包括定义基本类型和结构体类型的字典,并提供了一个示例代码,展示了如何解析C语言结构体。 ... [详细]
  • C语言常量与变量的深入理解及其影响
    本文深入讲解了C语言中常量与变量的概念及其深入实质,强调了对常量和变量的理解对于学习指针等后续内容的重要性。详细介绍了常量的分类和特点,以及变量的定义和分类。同时指出了常量和变量在程序中的作用及其对内存空间的影响,类似于const关键字的只读属性。此外,还提及了常量和变量在实际应用中可能出现的问题,如段错误和野指针。 ... [详细]
  • 恶意软件分析的最佳编程语言及其应用
    本文介绍了学习恶意软件分析和逆向工程领域时最适合的编程语言,并重点讨论了Python的优点。Python是一种解释型、多用途的语言,具有可读性高、可快速开发、易于学习的特点。作者分享了在本地恶意软件分析中使用Python的经验,包括快速复制恶意软件组件以更好地理解其工作。此外,作者还提到了Python的跨平台优势,使得在不同操作系统上运行代码变得更加方便。 ... [详细]
  • 全面介绍Windows内存管理机制及C++内存分配实例(四):内存映射文件
    本文旨在全面介绍Windows内存管理机制及C++内存分配实例中的内存映射文件。通过对内存映射文件的使用场合和与虚拟内存的区别进行解析,帮助读者更好地理解操作系统的内存管理机制。同时,本文还提供了相关章节的链接,方便读者深入学习Windows内存管理及C++内存分配实例的其他内容。 ... [详细]
  • 本文介绍了200个经典c语言源代码,包括函数的使用,如sqrt函数、clanguagefunct等。这些源代码可以帮助读者更好地理解c语言的编程方法,并提供了实际应用的示例。 ... [详细]
  • 本文讲述了作者从最初对软件工程的选择迷茫到逐渐喜欢并坚持学习的经历。作者在大学期间通过学习专业课和参与项目开发,不断挑战自己并取得成就感。虽然曾考虑过转专业和复读,但最终决定坚持学习软件工程,并为自己的未来努力奋斗。作者还提到了大学生活与自己最初的预期不同,但对此并没有太多抱怨。 ... [详细]
  • 本文介绍了GTK+中的GObject对象系统,该系统是基于GLib和C语言完成的面向对象的框架,提供了灵活、可扩展且易于映射到其他语言的特性。其中最重要的是GType,它是GLib运行时类型认证和管理系统的基础,通过注册和管理基本数据类型、用户定义对象和界面类型来实现对象的继承。文章详细解释了GObject系统中对象的三个部分:唯一的ID标识、类结构和实例结构。 ... [详细]
  • ejava,刘聪dejava
    本文目录一览:1、什么是Java?2、java ... [详细]
  • 《2017年3月全国计算机等级考试二级C语言上机题库完全版》由会员分享,可在线阅读,更多相关《2017年3月全国计算机等级考试二级C语言上机题库完全版( ... [详细]
  • 说到C语言的语句块,真是一堆血泪史。第一大坑就是优先级。刚工作那会儿,C的书没看几本,自信满满的认为C语言都会了,拿出搞ACM培养的豪情壮志,代码倒是写得爽,却到处留 ... [详细]
  • C语言自带的快排和二分查找
    Author🚹:CofCaiEmail✉️:cai.dongjunnexuslink.cnQQ😙:1664866311personalPage&#x ... [详细]
  • c语言基础编写,c语言 基础
    本文目录一览:1、C语言如何编写?2、如何编写 ... [详细]
author-avatar
ivanjjHelen
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有