try-catch如下编码块是一种很好的设计实践吗?也就是说,throw在try块中使用a 然后在catch块中捕获它.
try
{
if (someCondition){
throw new Exception("Go the the associated catch block!");
}
}
catch(Exception ex)
{
logError("I was thrown in the try block above");
}
Run Code Online (Sandbox Code Playgroud)
一般来说,如果它是最短的可写方法,那么它的设计还不错。但请注意,抛出异常通常需要大约 1 毫秒才能捕获。在这方面,这是一个性能问题。