A
try
...
catch
block is the way you do it:
try
{
... code which may cause a problem ...
}
catch (exceptionType exceptionVariable)
{
... code to handle the exception ...
}
The
exceptionVariable
allows you to access information on why the exception happened.
The
exceptionType
allows you to handle just the exceptions you can deal with: for all exceptions use
Exception
, but you could handle just SQL database exceptions with the SqlException class:
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
MyLoggingCode.WriteLine(ex.Message);
}
You should use the most specific Exception you can handle.
For more information, read up on
try-catch - C# Reference | Microsoft Docs[
^]