Class 方法重新运行错误代码,或者最好的方法是什么

Class 方法重新运行错误代码,或者最好的方法是什么,class,return,pseudocode,Class,Return,Pseudocode,我有一门课是这样的: class myclass { public function save($params){ // some operations // posible error return false; // some more code // posible error return false; // more code // if every

我有一门课是这样的:

class myclass {
    public function save($params){
        // some operations 
        // posible error
        return false;
        // some more code
        // posible error
        return false;
        // more code
        // if everything is ok
        return true;
    }
}
但是显示错误的最佳方法是什么,一个想法是让类返回数字,例如:

public function save($params) {
    // some operations
    // some error with the db
    return 1;
    // more code
    // some error with a table
    retunr 2;
    // more code
    // if everything is ok
    return 0;
}
当al调用此功能时,进行切换以显示错误:

$obj = new myclass();
$err = $obj->save($params);
switch($err) {
    case 1: echo 'error with the db'; break;
    case 2: echo 'error with some table'; break;
    default: echo 'object saved!';
}

这是写这篇文章的最好方式吗?或者还有另一种方法?

许多编程语言为您提供了抛出和捕获异常的选项。如果可用,这通常是一个更好的错误处理模型

public function save($params) throws SomeException {
    // some operations 
    if (posible error) 
       throw new SomeException("reason");
}


// client code
try {
  save(params);
} catch (SomeException e)  {
  // log, recover, abort, ...
}

异常的另一个优点是(至少在某些语言中)允许您访问堆栈跟踪和消息。

许多语言还有一组丰富的错误代码等待使用(例如Win32平台上的HRESULT)。我不打算采取一种立场来对抗另一种,但它们都能解决问题。:)是的,我会在类中放置一个异常,当我调用该类时,try-catch更干净,就像这样。