Try-Catch块异常处理中的异常处理 [英] Exception handling in Try-Catch block difference
问题描述
我知道,我们可以使用try-catch块来处理异常。但我对Try-Catch的使用有一些疑问。
有什么区别
I know, we can use try-catch block to handle exceptions. But I have some doubts in the usage of Try-Catch.
What is the difference between
try
{
//Some code
}
catch
{
}
和
and
try
{
//Some code
}
catch(Exception)
{
}
和
and
try
{
//Some code
}
catch(Exception oops)
{
}
在我的计划中,我需要抓住所有e xceptions,我不想记录它们。从上面提到的应该使用的Try-Catch块?
In my program, I need to catch all exceptions and I don''t want to log them. From the above mentioned Try-Catch blocks, which should be used?
推荐答案
第一个和第二个块之间没有区别,因为所有异常都继承自异常
。如果将异常
更改为另一个异常,例如OutOfMemoryException
,那么只有在执行时才会执行catch块中的代码。抛出OutOfMemoryException
的异常是。
在第三个块中,抛出的异常也是存储在变量中,因此您可以获取错误消息,例如:
There''s no difference between the first and the second block, because all exceptions inherit fromException
. If you changeException
into another exception,OutOfMemoryException
for example, then the code in the catch block will only be executed if the exception which is thrown aOutOfMemoryException
is.
In the third block, the exception which is thrown is also stored in a variable, so you can get the error message for example:
try
{
// some code
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // writes the error message to the console
}
< br $> b $ b
在我的程序中,我需要捕获所有异常,我不想记录它们。从上面提到的应该使用的Try-Catch块?
In my program, I need to catch all exceptions and I don''t want to log them. From the above mentioned Try-Catch blocks, which should be used?
如果你不需要指定一个异常类型,如果你不想记录它们,然后使用
If you don''t need to specify a exception type, and if you don''t want to log them, then use
try
{
// some code
}
catch
{
}
如果您需要指定例外类型,但如果您不想记录它们,然后使用
And if you need to specify an exception type, but if you don''t want to log them, then use
try
{
// some code
}
catch (OutOfMemoryException) // change OutOfMemoryException into the type of the exception which you need to specify
{
}
但如果你需要记录它们,那么使用
But if you need to log them, then use
catch (Exception ex) // change Exception into the type of the exception which you want to log
希望这会有所帮助。
Hope this helps.
这三种方式都是一样的。一般来说,除非您想要对异常执行某些操作,例如记录它,否则第一个块将正常工作。如果要以不同方式处理不同类型的错误,可以使用catch(Exception)语法。例如:
All three ways will work the same. Generally speaking, unless you want to do something with the exception, such as log it, the first block will work just fine. You can use the catch(Exception) syntax when you want to deal with different types of error in different ways. For example:
try
{
}
catch (AccessViolationException oops)
{
}
catch
{
}
意味着您将以特定方式处理AccessViolationException类型的错误,而您将以相同的方式处理所有其他类型的错误。
which means that you will deal in a specific way for errors of type AccessViolationException while you will deal in the same way with all other types of errors.
这篇关于Try-Catch块异常处理中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!