Skip to content

Latest commit

 

History

History
74 lines (55 loc) · 1.43 KB

File metadata and controls

74 lines (55 loc) · 1.43 KB

Error Handling

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.

Throwing Exceptions

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...
}

Catching Exceptions

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}");
}

Rethrowing Exceptions

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

nothrow modifier mark function with strong safety guarantees.

If Exception throws in function, that marked with nothrow modifier, program will be aborted.

void Process(int x) nothrow
{
    if (x < 0) throw new Exception();
}

Process(-1); // program will be aborted