Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Throw and rethrow patterns in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Throw and Rethrow Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of rethrowing an exception with throw;
What will be the output of this C# program when an exception is rethrown using throw; inside the catch block?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        try {
            ThrowException();
        } catch (Exception ex) {
            Console.WriteLine("Caught: " + ex.Message);
            try {
                throw;
            } catch (Exception e) {
                Console.WriteLine("Rethrown caught: " + e.Message);
            }
        }
    }
    static void ThrowException() {
        throw new InvalidOperationException("Original error");
    }
}
A
Caught: Original error
Rethrown caught: Original error
B
Caught: Original error
Rethrown caught: Exception of type 'System.Exception' was thrown.
C
Caught: Original error
Rethrown caught: System.InvalidOperationException
D
Caught: Original error
Rethrown caught: System.InvalidOperationException: Original error
Attempts:
2 left
💡 Hint
Remember that using throw; preserves the original exception and its message.
Predict Output
intermediate
2:00remaining
Effect of throw ex; vs throw; on stack trace
Consider this code snippet. What will be the output regarding the exception message and stack trace when using throw ex; instead of throw; inside the catch block?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        try {
            ThrowException();
        } catch (Exception ex) {
            Console.WriteLine("Caught: " + ex.Message);
            try {
                throw ex; // Change this line to 'throw;' to compare
            } catch (Exception e) {
                Console.WriteLine("Rethrown caught: " + e.Message);
                Console.WriteLine(e.StackTrace.Split('\n')[0]);
            }
        }
    }
    static void ThrowException() {
        throw new InvalidOperationException("Original error");
    }
}
A
Caught: Original error
Rethrown caught: Original error
 at Program.Main() ...
B
Caught: Original error
Rethrown caught: Exception of type 'System.Exception' was thrown.
C
Caught: Original error
Rethrown caught: Original error
 at Program.ThrowException() ...
D
Caught: Original error
Rethrown caught: Original error
 at Program.Main() ... (stack trace reset)
Attempts:
2 left
💡 Hint
Using throw ex; resets the stack trace to the current throw point.
🔧 Debug
advanced
2:00remaining
Identify the problem with rethrowing exception
This code tries to catch and rethrow an exception but causes unexpected behavior. What is the main problem?
C Sharp (C#)
try {
    DoWork();
} catch (Exception ex) {
    Log(ex.Message);
    throw ex;
}

void DoWork() {
    throw new Exception("Error in DoWork");
}

void Log(string message) {
    Console.WriteLine("Log: " + message);
}
AThe Log method causes a runtime error.
BThe catch block does not catch the exception properly.
CUsing 'throw ex;' resets the stack trace, losing original error location.
DThe exception message is lost after rethrowing.
Attempts:
2 left
💡 Hint
Consider how 'throw ex;' affects the stack trace compared to 'throw;'.
🧠 Conceptual
advanced
2:00remaining
Why prefer 'throw;' over 'throw ex;' when rethrowing?
Which of the following best explains why using throw; is preferred over throw ex; when rethrowing an exception in C#?
AThere is no difference; both behave identically.
B<code>throw;</code> preserves the original stack trace, aiding debugging, while <code>throw ex;</code> resets it.
C<code>throw;</code> creates a new exception object, while <code>throw ex;</code> reuses the old one.
D<code>throw ex;</code> preserves the original stack trace, while <code>throw;</code> resets it.
Attempts:
2 left
💡 Hint
Think about what happens to the stack trace in each case.
Predict Output
expert
2:00remaining
Output when rethrowing inside nested try-catch
What is the output of this C# program that uses nested try-catch blocks and rethrows exceptions?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        try {
            try {
                throw new Exception("Inner exception");
            } catch (Exception ex) {
                Console.WriteLine("Caught inner: " + ex.Message);
                throw;
            }
        } catch (Exception ex) {
            Console.WriteLine("Caught outer: " + ex.Message);
        }
    }
}
A
Caught inner: Inner exception
Caught outer: Inner exception
BCaught inner: Inner exception
CCaught outer: Inner exception
DNo output, program crashes
Attempts:
2 left
💡 Hint
The inner catch rethrows the exception to the outer catch.

Practice

(1/5)
1. What does the throw statement do in C# exception handling?
easy
A. It logs the error without stopping the program.
B. It ignores the error and continues execution.
C. It stops the program and signals an error.
D. It automatically fixes the error and resumes.

Solution

  1. Step 1: Understand the purpose of throw

    The throw statement is used to signal that an error has occurred and to stop normal program flow.
  2. Step 2: Recognize program behavior on throw

    When throw is executed, the program stops and looks for a matching catch block or terminates if none is found.
  3. Final Answer:

    It stops the program and signals an error. -> Option C
  4. Quick Check:

    throw stops program = C [OK]
Hint: Throw always stops execution and signals an error [OK]
Common Mistakes:
  • Thinking throw continues program normally
  • Confusing throw with logging
  • Assuming throw fixes errors automatically
2. Which of the following is the correct syntax to rethrow an exception in a catch block without changing it?
easy
A. throw catch;
B. throw ex;
C. throw new Exception();
D. throw;

Solution

  1. Step 1: Identify rethrow syntax

    To rethrow the caught exception preserving the original stack trace, use throw; without specifying the exception variable.
  2. Step 2: Understand difference from throw ex;

    throw ex; resets the stack trace, which is not a pure rethrow.
  3. Final Answer:

    throw; -> Option D
  4. Quick Check:

    Rethrow syntax = throw; [OK]
Hint: Use plain 'throw;' to rethrow without losing stack trace [OK]
Common Mistakes:
  • Using 'throw ex;' which resets stack trace
  • Trying to throw a new exception instead
  • Using invalid syntax like 'throw catch;'
3. What will be the output of the following C# code?
try {
  throw new Exception("Error 1");
} catch (Exception ex) {
  Console.WriteLine(ex.Message);
  throw;
}
medium
A. Error 1 printed, then program terminates with the same exception.
B. No output, program silently terminates.
C. Error 1 printed, then program continues normally.
D. Compilation error due to missing catch block.

Solution

  1. Step 1: Analyze the try block

    The try block throws an exception with message "Error 1".
  2. Step 2: Analyze the catch block

    The catch block prints the exception message, then rethrows the same exception using throw;.
  3. Step 3: Understand program flow after rethrow

    Since the exception is rethrown and not caught again, the program terminates with the same exception after printing.
  4. Final Answer:

    Error 1 printed, then program terminates with the same exception. -> Option A
  5. Quick Check:

    Print then rethrow = B [OK]
Hint: Rethrow after print causes termination with printed message [OK]
Common Mistakes:
  • Assuming program continues after rethrow
  • Thinking no output is printed
  • Confusing rethrow with new exception creation
4. Identify the error in this code snippet:
try {
  // some code
} catch (Exception ex) {
  throw ex;
}
medium
A. Try block must have a finally block.
B. Using throw ex; resets the stack trace, losing original error info.
C. Cannot catch Exception type directly.
D. Missing semicolon after throw ex.

Solution

  1. Step 1: Understand throw ex; effect

    Using throw ex; throws the exception but resets the stack trace, losing original error location.
  2. Step 2: Identify correct rethrow method

    To preserve stack trace, use throw; without specifying the exception variable.
  3. Final Answer:

    Using throw ex; resets the stack trace, losing original error info. -> Option B
  4. Quick Check:

    Throwing exception variable resets stack trace = D [OK]
Hint: Use 'throw;' not 'throw ex;' to keep original stack trace [OK]
Common Mistakes:
  • Thinking 'throw ex;' preserves stack trace
  • Believing finally block is mandatory
  • Assuming Exception cannot be caught directly
5. You want to catch an exception, add extra info, and then rethrow it preserving the original stack trace. Which pattern is correct?
try {
  // code
} catch (Exception ex) {
  // add info
  ???
}
hard
A. throw new Exception("Extra info", ex);
B. throw ex;
C. throw;
D. throw new Exception(ex.Message);

Solution

  1. Step 1: Understand wrapping exceptions

    To add extra info, create a new exception with the original as inner exception: new Exception("Extra info", ex).
  2. Step 2: Preserve original stack trace

    This wrapping keeps original exception details inside the new one, preserving context.
  3. Step 3: Why not other options?

    throw ex; resets stack trace, throw; rethrows original without extra info, and throw new Exception(ex.Message); loses original exception object.
  4. Final Answer:

    throw new Exception("Extra info", ex); -> Option A
  5. Quick Check:

    Wrap with new Exception and inner ex = A [OK]
Hint: Wrap original in new Exception to add info and preserve trace [OK]
Common Mistakes:
  • Using 'throw ex;' which loses stack trace
  • Using 'throw;' which loses added info
  • Creating new Exception without inner exception