使用try-catch:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
}
或者,如果要捕获指定的异常,请执行以下操作:
try {
// code here
} catch (/* exception class here */) {
// do something or nothing if caught
}
例如,如果要捕获NullReferenceException,请执行以下操作:
try {
// code here
} catch (NullReferenceException) {
// do something or nothing if caught
}
如果要使用异常数据,请将异常定义为变量,如下所示:
try {
// code here
} catch (Exception e) {
// do something or nothing if caught
}
在Visual Studio中,您可以通过键入
try
并双击Tab键来插入try-catch代码段。
最后还有try-catch-finally。例:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
} finally {
// perform some cleanup here
}
在Visual Studio中,您可以键入
tryf
和双击Tab键以插入try-catch-finally代码段。
您也可以使用try-finally进行一些清理,而不会出现任何错误:
try {
// code here
} finally {
// perform some cleanup here
}
在MSDN上有关
try-catch,
try-finally和
try-catch-finally的更多信息。
但是,即使发生错误,也意味着有问题。 Google关于它的一些信息。