- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Java如何自定义异常打印非堆栈信息详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
前言 。
在学习java的过程中,想必大家都一定学习过异常这个篇章,异常的基本特性和使用这里就不再多讲了。什么是异常?我不知道大家都是怎么去理解的,我的理解很简单,那就是不正常的情况,比如我现在是个男的,但是我却有着女人所独有的东西,在我看来这尼玛肯定是种异常,简直不能忍。想必大家都能够理解看懂,并正确使用.
但是,光学会基本异常处理和使用不够的,在工作中出现异常并不可怕,有时候是需要使用异常来驱动业务的处理,例如: 在使用唯一约束的数据库的时候,如果插入一条重复的数据,那么可以通过捕获唯一约束异常duplicatekeyexception来进行处理,这个时候,在server层中就可以向调用层抛出对应的状态,上层根据对应的状态再进行处理,所以有时候异常对业务来说,是一个驱动方式.
有的捕获异常之后会将异常进行输出,不知道细心的同学有没有注意到一点,输出的异常是什么东西呢?
下面来看一个常见的异常:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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
)
|
一个空指针异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
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 方法呢? 我们首先来看源码是怎么一回事. 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
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里面是怎么回事呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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里面是怎么一回事
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
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 < 0 ||
* index >= 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方法就可以不从栈中去获取异常信息,直接输出,这样对系统和程序来说,相对就没有那么”重”, 是一个优化性能的非常好的办法。那么如果出现自定义异常那么是什么样的呢?请看下面吧
1
2
3
4
5
6
7
8
9
|
@test
public
void
testexception(){
try
{
string str =
null
;
system.out.println(str.charat(
0
));
}
catch
(exception e){
throw
new
appexception(
"000001"
,
"空指针异常"
);
}
}
|
那么在异常异常的时候,系统将会打印我们自定义的异常信息
1
2
|
000001
[空指针异常]
process finished with exit code -
1
|
所以特别简洁,优化了系统程序性能,让程序不这么“重”, 所以对于性能要求特别要求的系统。赶紧自己的自定义异常吧! 。
总结 。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我的支持.
原文链接:https://wangchangchung.github.io/2018/04/18/Java自定义异常打印非堆栈信息/ 。
最后此篇关于Java如何自定义异常打印非堆栈信息详解的文章就讲到这里了,如果你想了解更多关于Java如何自定义异常打印非堆栈信息详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
出于好奇 - 我知道有 LAMP - Linux、Apache、MySQL 和 PHP。但是还有哪些其他 Web 堆栈替代方案的缩写呢?像 LAMR - Linux、Apache、MySQL Ruby
我有以下代码。 var stackMapIn = []; var stackMapOut = []; var stackBack = []; stackMapOut.push("m1"); $scop
我遇到了导致我的堆栈无法恢复的情况,我别无选择,只能将其删除。使用完全相同的模板,我继续创建了另一个同名的堆栈。 The following resource(s) failed to create:
这是我第一次查看 Node 堆栈,自从我学习使用 Ruby on Rails 进行 Web 开发以来,我对一些基本的东西有点困惑。我了解 Rails 目录是什么样的。 demo/ ..../app .
本文实例讲述了C语言使用深度优先搜索算法解决迷宫问题。分享给大家供大家参考,具体如下: 深度优先搜索 伪代码 (Pseudocode)如下: ?
我正在按照指南 here ,它告诉我: The stack setup will download the compiler if necessary in an isolatedlocation (
同时 trying to debug a different question ,我安装了一个似乎与我安装的其他一些软件包冲突的软件包。 我跑了 $ stack install regex-pcre-
我花了几个小时创建了一个方法,该方法将从堆栈 s1 中获取 null 元素,并将它们放入 s2 中。然后该类应该打印堆栈。方法如下 import net.datastructures.ArraySta
我有一个类Floor,它有一个Stack block ,但我不知道如何初始化它。我曾尝试过这样的: public class Floor { private Stack stack;
我知道这个问题已经问过很多次了,但搜索一个小时后我仍然遇到问题。 我想使用一个 lifo 堆栈,它可以存储最大数量的元素。达到最大数量后,首先删除该元素并将其替换为新元素,这样在第一次弹出时我可以获取
我需要编写一个方法,压缩以执行以下操作; 目标compress方法是从栈s1中移除所有null元素。剩余(非空)元素应按其初始顺序保留在 s1 上。辅助堆栈 s2 应用作s1 中元素的临时存储。在该方
我正在尝试验证以下代码发生的顺序。 function square(n) { return n * n; } setTimeout(function(){ console.log("H
我需要一个字符数组,其中包含基于特定文件夹中文件数量的动态数量的字符数组。我能够通过初始化 char (*FullPathNames)[MAX_FILENAME_AND_PATHNAME_LENGTH
我正在编写一些日志逻辑并想要进行一些缩进。了解是否存在任何函数调用或某个函数是否已完成的最简单方法是查看堆栈/帧的当前地址。让我们假设堆栈颠倒增长。然后,如果 log() 调用中的堆栈地址小于前一次调
所以内存分段在x86-64中被放弃了,但是当我们使用汇编时,我们可以在代码中指定.code和.data段/段,并且还有堆栈指针寄存器。 还有堆栈段、数据段和代码段寄存器。 代码/数据/堆栈的划分是如何
void main() { int x = 5; // stack-allocated Console.WriteLine(x); } 我知道 x 是堆栈分配的。但是关于 x 的堆栈中
这是我关于 SO 的第一个问题。这可能是一个愚蠢的问题,但到目前为止我还没弄明白。 考虑下面的程序 Reader.java: public class Reader { public
java中有没有一种快速的方法来获取嵌套/递归级别? 我正在编写一个函数来创建组及其成员的列表。成员也可以是团体。我们最终可能会得到一组循环的组/成员。 我想在某个任意级别停止。 我知道我可以将变量保
考虑以下代码: struct A{...}; A a[100]; A* pa = new A[100]; delete[] pa; a/pa 元素的销毁顺序是由标准定义的还是实现定义的(对于第二种情况
我在下面有一些代码。此代码是一个基本的压入/弹出堆栈类,我将其创建为模板以允许某人压入/弹出堆栈。我有一个家庭作业,我现在要做的是创建一个具有多个值的堆栈。 所以我希望能够创建一个基本上可以发送三个整
我是一名优秀的程序员,十分优秀!