Use try-catch:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
}
Or, if you want to catch a specified exception, do this:
try {
// code here
} catch (/* exception class here */) {
// do something or nothing if caught
}
For instance, if you want to catch NullReferenceException, then do this:
try {
// code here
} catch (NullReferenceException) {
// do something or nothing if caught
}
If you want to use exception data, define exception as a variable, like this:
try {
// code here
} catch (Exception e) {
// do something or nothing if caught
}
In Visual Studio, you can insert a try-catch snippet by typing try
and double-hitting Tab key.
There's also try-catch-finally. Example:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
} finally {
// perform some cleanup here
}
In Visual Studio, you can type tryf
and double-hit Tab key to insert a try-catch-finally snippet.
You can also just perform some cleanup using try-finally without getting any error:
try {
// code here
} finally {
// perform some cleanup here
}
More info on MSDN about try-catch, try-finally and try-catch-finally.
But still, if an error occurs, that mean something is wrong. Google some information about it.