我为我的应用程序不期望的每个条件创建了异常. UserNameNotValidException
,PasswordNotCorrectException
等等.
但是我被告知我不应该为这些条件创建例外.在我的UML中,那些是主流的例外,为什么它不应该是例外?
创建例外的任何指导或最佳实践?
Java异常处理和使用assert
条件之间有什么区别?
众所周知,Assert有两种类型.但什么时候应该使用assert
关键字?
在面向对象的样式中,依赖关系倾向于被反转,构造函数具有不同的Spartan角色.它唯一的工作是确保对象初始化为满足其基本不变量的状态(换句话说,它确保对象实例以有效状态启动,而不是更多).
这是一个类的基本示例.在创建类时,我传入需要解析的HTML,然后设置类属性.
OrderHtmlParser
{
protected $html;
protected $orderNumber;
public function __construct($html)
{
$this->html = $html;
}
public function parse()
{
$complexLogicResult = $this->doComplexLogic($this->html);
$this->orderNumber = $complexLogicResult;
}
public function getOrderNumber()
{
return $this->orderNumber;
}
protected function doComplexLogic($html)
{
// ...
return $complexLogicResult;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用它
$orderparser = new OrderHtmlParser($html);
$orderparser->parse()
$orderparser->getOrderNumber();
Run Code Online (Sandbox Code Playgroud)
我使用一个parse
函数,因为我不希望构造函数做任何逻辑,因为上面的文章和本文都说这是一个糟糕的做法.
public function __construct($html)
{
$this->html = $html;
$this->parse(); // bad
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我不使用该parse
方法,那么我的所有属性(在此示例中只是一个)将返回null
.
这被称为"无效状态"中的对象吗?
另外,有点感觉 …
在Java中:
class Base {
public Base() { System.out.println("Base::Base()"); virt(); }
void virt() { System.out.println("Base::virt()"); }
}
class Derived extends Base {
public Derived() { System.out.println("Derived::Derived()"); virt(); }
void virt() { System.out.println("Derived::virt()"); }
}
public class Main {
public static void main(String[] args) {
new Derived();
}
}
Run Code Online (Sandbox Code Playgroud)
这将输出
Base::Base()
Derived::virt()
Derived::Derived()
Derived::virt()
Run Code Online (Sandbox Code Playgroud)
但是,在C++中,结果是不同的:
Base::Base()
Base::virt() // ? Not Derived::virt()
Derived::Derived()
Derived::virt()
Run Code Online (Sandbox Code Playgroud)
(有关C++代码,请参阅http://www.parashift.com/c++-faq-lite/calling-virtuals-from-ctors.html)
什么导致Java和C++之间的这种差异?这是vtable初始化的时间吗?
编辑:我确实理解Java和C++机制.我想知道的是这个设计决定背后的见解.
在调试 Rust 程序时,是否可以在Err()
创建值时中断执行?
这与打破其他语言(C++、Javascript、Java 等)中的异常的目的相同,因为它向您展示了错误的实际来源,而不仅仅是解开它的地方,这通常不是很有用。
我正在使用 LLDB,但对任何调试器的答案感兴趣。在Err
我感兴趣的是,在深SERDE产生,所以我真的不能修改任何代码。
上下文:我正在为学校写一个信号量类,其中一个要求是它可能没有用负值初始化.
现在我的构造函数抛出异常:
/**
* Constructor
*/
public Semaphore(int value) throws Exception
{
if (value < 0)
throw new Exception("Negative value provided for initial constructor.");
this.value = value;
}
Run Code Online (Sandbox Code Playgroud)
处理异常以实例化信号量对我来说似乎过于沉重,所以我正在考虑将任何负值静默设置为零,即:
/**
* Constructor
*/
public Semaphore(int value)
{
if (value < 0)
this.value = 0;
else
this.value = value;
}
Run Code Online (Sandbox Code Playgroud)