是否是使构造函数抛出异常的好习惯? [英] Is it good practice to make the constructor throw an exception?

查看:143
本文介绍了是否是使构造函数抛出异常的好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很好的做法,使构造函数抛出异常?
例如,我有一个类 Person ,我有 age 作为它的唯一属性。现在
我提供类作为

Is it a good practice to make the constructor throw an exception? For example I have a class Person and I have age as its only attribute. Now I provide the class as

class Person{
  int age;
  Person(int age) throws Exception{
   if (age<0)
       throw new Exception("invalid age");
   this.age = age;
  }

  public void setAge(int age) throws Exception{
  if (age<0)
       throw new Exception("invalid age");
   this.age = age;
  }
}


推荐答案

在构造函数中的异常不是坏习惯。事实上,对于构造函数来说,这是只有合理的方式来指示有问题;例如

Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.

但是显式声明或抛出 java.lang.Exception 几乎总是不好的做法。

However explicitly declaring or throwing java.lang.Exception is almost always bad practice.

您应该选择一个与发生的异常情况相匹配的异常类。如果你抛出 Exception ,调用者很难将这个异常与任何数量的其他可能的声明和未声明的异常分离。这使错误恢复困难,如果调用者选择传播异常,问题只是蔓延。

You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.

assert 用于检查参数。这个问题是可以通过JVM命令行设置来打开和关闭 assert 断言的检查。使用断言检查内部不变式是可以的,但使用它们来实现在你的javadoc中指定的参数检查是不是一个好主意...因为这意味着你的方法将只有严格实施规范时,启用断言检查。

Someone suggested using assert for checking arguments. The problem with this is that checking of assert assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.

assert 的第二个问题是如果断言失败,则 AssertionError 将被抛出,并且收到的智慧是,它是一个坏主意试图捕获错误及其任何子类型。

The second problem with assert is that if an assertion fails, then AssertionError will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error and any of its subtypes.

这篇关于是否是使构造函数抛出异常的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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