Skip to content
Learn Netverks

Lesson

Step 27/36 75% through track

exception-handling-csharp

Exception handling

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Exception handling: the syntax, patterns, and safety habits you need before advancing in C#.

Teams still ship Exception handling in C# codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Exception handling in contexts like: .NET services, Unity games, and Windows-centric tooling.

Write C# with Console.WriteLine (top-level or Program), click Run on server—the dev runner uses dotnet build/run on a temp net8 project (requires .NET SDK; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

C# uses exceptions for exceptional error paths—similar to Java but without checked exceptions. Combine try/catch/finally with using for deterministic resource cleanup via IDisposable.

try / catch / finally

try {
    throw new InvalidOperationException("failed");
} catch (InvalidOperationException ex) {
    Console.WriteLine(ex.Message);
} finally {
    Console.WriteLine("cleanup");
}

Custom exceptions

class AppException : Exception {
    public AppException(string message) : base(message) { }
}

Throw specific types; catch the most specific exception first. Use exceptions for unexpected failures—not routine control flow.

Important interview questions and answers

  1. Q: Exceptions vs Result types?
    A: Exceptions unwind the stack for rare failures; Result/either patterns suit expected errors in functional-style APIs.
  2. Q: finally vs using?
    A: using calls Dispose deterministically; finally runs on all exit paths including exceptions.

Self-check

  1. What runs in finally when an exception is thrown?
  2. Base type for catching all managed exceptions?

Tip: Catch specific exceptions first—avoid empty catch blocks that swallow errors and hide bugs in production.

Interview prep

finally purpose?

Runs whether or not an exception is thrown—use for cleanup; prefer using for disposable resources.

throw vs throw ex?

throw; preserves the original stack trace; throw ex; resets it—rethrow with bare throw.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • finally always?
  • throw ex bad?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump