Summary - Exception basics
Combine try/catch/finally and a custom exception to write a bank account class.
Summary - Exception basics
In this group you learned the basics of exception handling. The try block holds risky code, catch handles errors, and finally always cleans up. You throw exceptions with throw and rethrow with throw;.
The Exception class's Message, StackTrace and InnerException properties help with debugging. For your domain's specific errors, you can write classes derived from Exception. In the next exercise you will try them all together.
Practical tips
A few tips on exception handling: start with the most specific catch type and leave the most general Exception for last. When rethrowing, use throw; instead of throw ex;. Use finally for resource cleanup.
Define custom exception classes only when you truly need domain-specific handling. Instead of showing the raw stack trace to the user, offer a meaningful message. These tips help you build error handling that is both safe and readable.
Exercise Combine try/catch/finally
Inside a try block, divide with int c = a / b;. In a catch (DivideByZeroException) block, print "Division by zero error" with Console.WriteLine. In a finally block, print "Done" with Console.WriteLine.
Show example solution
Write try { int c = a / b; } catch (DivideByZeroException) { Console.WriteLine("Division by zero error"); } finally { Console.WriteLine("Done"); }
Example solution:
using System;
class Program
{
static void Main()
{
int a = 10;
int b = 0;
try
{
int c = a / b;
}
catch (DivideByZeroException)
{
Console.WriteLine("Division by zero error");
}
finally
{
Console.WriteLine("Done");
}
}
}
Test yourself
-
Match each keyword with its job
- try
- Risky code
- catch
- Catches errors
- finally
- Cleanup
- throw
- Throws an exception
-
Which is true for exception handling?
try { ... } catch (Exception ex) { ... }- Only try is enough
- try cannot exist without catch
- catch cannot exist without finally
- try and catch are used together
Show answer
try and catch are used together — Correct! try and catch are used together; finally is optional.