Throwing Exceptions

How to signal errors in your own code

Posted by Rodrigo Castro on December 1, 2024

Sometimes, your code needs to tell the user “something went wrong.” You do this by throwing exceptions.

🏗️ Throwing an Exception

1
2
3
4
5
6
void Divide(int a, int b)
{
    if (b == 0)
        throw new ArgumentException("Cannot divide by zero!");
    Console.WriteLine(a / b);
}

🧑‍💻 Why Throw Exceptions?

  • To signal that something is wrong and the program should not continue as usual.
  • Makes bugs easier to find.

🛡️ Handling Thrown Exceptions

Catch them where it makes sense:

1
2
3
4
5
6
7
8
try
{
    Divide(10, 0);
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message); // "Cannot divide by zero!"
}

💡 Try It!

Write a method that throws an exception if a string is null or empty:

1
2
3
4
5
6
void PrintName(string name)
{
    if (string.IsNullOrEmpty(name))
        throw new ArgumentException("Name cannot be empty.");
    Console.WriteLine(name);
}

Next: Custom exception classes!