我知道,我们可以使用 try-catch block 来处理异常。但是我对Try-Catch的用法有些疑惑。 有什么区别
try
{
//Some code
}
catch
{
}
和
try
{
//Some code
}
catch(Exception)
{
}
和
try
{
//Some code
}
catch(Exception oops)
{
}
在我的程序中,我需要捕获所有异常并且我不想记录它们。从上面提到的 Try-Catch block 中,应该使用哪个?
最佳答案
从框架 2.0 开始,使用不带参数的 catch
不再有用,因为所有非托管异常都包含在托管异常中。在此之前,您可以使用它来捕获非托管代码抛出的异常。
如果您不想使用异常的任何信息,您可以只指定异常的类型,但通常您需要一个名称以便您可以获取信息:
try {
// some code
} catch(Exception) {
// i don't care about any information in the Exception object, just the type
}
对比
try {
// some code
} catch(Exception ex) {
// use some information from the exception:
MessageBox.Show("Internal error", ex.Message);
}
您应该始终尝试使用尽可能具体的异常类型,因为这样可以更轻松地处理异常。然后您可以添加不太具体的类型来处理其他异常。示例:
try {
// some database code
} catch(SqlException ex) {
// something in the database call went wrong
} catch(Exception ex) {
// something else went wrong
}
关于c# - 异常处理 Try-Catch block 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874493/