与Java中的异常vs Throwable相关联的开销 [英] Overhead associated with Exception vs Throwable in Java

查看:175
本文介绍了与Java中的异常vs Throwable相关联的开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道

throw new Exception();

有一个相当大的开销,因为它创建了一个完整的stackTrace等。

has a pretty large overhead, since it creates a full stackTrace, etc.
Does

throw new Throwable();

提出同样的问题?这个行为是继承还是抛出一个Throwable有一个较小的(o no)开销?

present the same problem? Is this behaviour inherited, or does throwing a Throwable has a smaller (o no) overhead?

编辑

从一个分析师的观点,用户插入错误的密码是程序的正常执行顺序的例外。所以如果我有:

EDIT
From an analyst point of view, a user inserting wrong password is an exception to the normal execution order of a program. So if I have:

public Session newSession() {  
  validate_user_and_password();   
}

抛出UserNotValidException会从分析人员的观点。

返回 null 0 如果您的代码很不错,只是听起来不正确抽象。我只是想知道我是否可以在代码中实际实现这一点,或者我必须将它放在理论上。

throwing a UserNotValidException would sound correct from an analysts point of view.
Returning null or 0 just sounds incorrect if your code has pretty good abstraction. I just wanted to know if I could actually implement this in code, or if I'd have to just leave it to theory.

编程点之间有很大的区别 - 视图异常和分析器视点异常。

There's a good difference between programming-point-of-view exception and analyst-point-of-view exception.

注意:我给了一个非常简单而愚蠢的例子,这不是我的情况。

注2:我知道返回 null 将是普通的东西,但是我需要有正确的抽象和OO代码,

Note: I've given a really simple and silly example, this is not quite my case.
Note 2: I know returning null would be the ordinary thing, but I'm required to have properly abstracted and OO code, and, personally, I see no harm in this.

推荐答案

Throwable 还会创建一个堆栈跟踪创建时从 java文档 Throwable

Throwable also creates a stacktrace when it's created. From the java docs for Throwable:


throwable在创建时包含其线程的执行堆栈的快照

throwable contains a snapshot of the execution stack of its thread at the time it was created.

因此,关于创建堆栈跟踪的开销方面, Exception Throwable

So in terms of overhead with regards to creating a stacktrace, there should be no difference between Exception and Throwable.

如果您使用特殊事件应该是),那么你不应该太关心堆栈跟踪的开销。运行代码中很少出现异常事件。因此,异常不应以任何重要的方式影响正常代码的性能。

If you are using exceptions for "exceptional events" (as you should be), then you shouldn't be too concerned with the overhead of a stacktrace. An exceptional event occurs rarely in running code. So Exceptions shouldn't impact the performance of normal code in any significant way.

这篇关于与Java中的异常vs Throwable相关联的开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆