Program errors are intended to be exceptional.
You should use exceptions for conditions that are outside the normal flow of the program, such as I/O failures, resource exhaustion or logic violations.
All exceptions are defined as struct's inheriting Exception abstract struct.
You use the throw keyword followed to initiate an error.
struct NetworkError : Exception
{
public int Code;
}
void SendData(int data)
{
if (data < 0)
throw new NetworkError(404);
// standard logic...
}Use try and catch blocks to capture and handle exceptions.
try
{
var connection = new Connection();
SendData(-1);
}
catch (NetworkError e)
{
Console.WriteLine($"Error occurred with code: {e.Code}");
}You can use throw in try-catch block to throw Exception to next block.
try
{
var connection = new Connection();
SendData(-1);
}
catch (NetworkError e)
{
Console.WriteLine($"Error occurred with code: {e.Code}");
throw; // throw to next try-catch block
}nothrow modifier mark function with strong safety guarantees.
If
Exceptionthrows in function, that marked withnothrowmodifier, program will be aborted.
void Process(int x) nothrow
{
if (x < 0) throw new Exception();
}
Process(-1); // program will be aborted