0
0
C Sharp (C#)programming~5 mins

Throw and rethrow patterns in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Throwing and rethrowing help you handle errors in your program. You can stop the program when something goes wrong or pass the error up to fix it later.

When you want to stop the program because something unexpected happened.
When you catch an error but want to add more information before passing it on.
When you want to log an error and then let another part of the program handle it.
When you want to clean up resources before passing the error up.
When you want to keep the original error details while handling it in multiple places.
Syntax
C Sharp (C#)
throw new Exception("Error message");

// To rethrow an existing exception inside a catch block:
throw;

// Or to throw a new exception with the caught one as inner:
throw new Exception("New message", ex);

throw creates a new error or passes an existing one.

Use throw; alone inside a catch to keep the original error details.

Examples
This stops the program and shows a new error message.
C Sharp (C#)
throw new Exception("Something went wrong");
This catches an error and immediately passes it up without changing it.
C Sharp (C#)
try {
    // code that may fail
} catch (Exception ex) {
    throw; // rethrows the same error
}
This catches an error, adds a new message, and keeps the original error inside.
C Sharp (C#)
try {
    // code that may fail
} catch (Exception ex) {
    throw new Exception("New error", ex); // wraps original error
}
Sample Program

This program shows how to throw a new error with an original error inside, and how to rethrow an error to keep its details.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        try {
            CauseError();
        } catch (Exception ex) {
            Console.WriteLine("Caught in Main: " + ex.Message);
            throw; // rethrow to keep original error
        }
    }

    static void CauseError() {
        try {
            throw new Exception("Original error");
        } catch (Exception ex) {
            Console.WriteLine("Caught in CauseError: " + ex.Message);
            throw new Exception("Wrapped error", ex); // throw new with inner
        }
    }
}
OutputSuccess
Important Notes

Use throw; alone to keep the original stack trace.

Throwing a new exception with the old one inside helps add context.

Rethrowing without losing details helps debugging later.

Summary

Throw stops the program with an error.

Rethrow passes the caught error up without changing it.

You can wrap errors to add more information.