为什么我们需要创建自定义异常.NET?
.NET?
特定的自定义异常允许您为 catch 语句隔离不同的错误类型。异常处理的常见结构是这样的:
try {} catch (Exception ex) {}
这抓住了all异常,与类型无关。但是,如果您有自定义异常,则可以为每种类型设置单独的处理程序:
try {} catch (CustomException1 ex1) { //handle CustomException1 type errors here } catch (CustomException2 ex2) { //handle CustomException2 type errors here } catch (Exception ex) { //handle all other types of exceptions here }
因此,特定异常可以让您更好地控制异常处理。不仅自定义异常共享此优势,.NET 系统库中的所有其他异常类型也共享此优势。