【发布时间】:2017-12-08 13:01:09
【问题描述】:
我正在尝试学习 java,但在理解异常的工作原理方面存在一些问题。
我们什么时候需要在条件后使用 throw? 举个例子
public Ex(String name, String prenom, int age) throws exceptionex {
if (name.length() < 3 && prenom.length() < 3 && age < 1) throw new exceptionex();
this.age = age;
this.name = name;
this.prenom = prenom;
}
excepetionex 是一个空类,它扩展了Exception。
上一个例子和这个例子有什么区别?
public Ex(String name, String prenom, int age) {
if (name.length() < 3 && prenom.length() < 3 && age < 1)
try {
throw new exceptionex();
} catch (exceptionex e) {
e.printStackTrace();
}
this.age = age;
this.name = name;
this.prenom = prenom;
}
printstackTrace 到底是做什么的?
如果我们想自定义异常(exeptionex 这里)或者我们可以只使用(throw new Exception),我们是否总是需要创建另一个类?
我用谷歌搜索了我的问题,但没有找到我能理解的答案,可能是因为我是新手,或者因为英语不是我的母语,我需要尽可能简单的解释。
【问题讨论】:
-
你不需要抛出异常来打印它的堆栈跟踪:
new exceptionex().printStackTrace()做的差不多。 -
“有什么区别”第一个阻止您创建
Ex的无效实例;第二个打印一些东西到stderr,然后无论如何创建对象。 -
首先请记住java类名及其构造函数要大写。
-
"
printstackTrace到底是做什么的?" 学习阅读docs,这是您的大部分答案所在。 -
如果 if 条件为真,基本上第一个只是抛出一个异常,“取消”构造函数。第二个做同样的事情,但随后捕获异常,将堆栈跟踪打印到 stderr 并继续构造函数。
标签: java exception try-catch throw