Traditional versus functional error handling comparison
Every developer experiences it sooner or later: running into an error while coding. But as the coding world has changed, so has the way we deal with these problems. Let’s look at the clear differences between the old and new ways of handling errors in C# and understand why this new approach is becoming more popular.
The traditional way
In traditional OOP, exceptions are the go-to mechanism:
- Throwing exceptions: We rely on system or custom exceptions when things go wrong:
public User GetUser(int id) { if (id < 0) throw new ArgumentOutOfRangeException(nameof(id)); // ... fetch the user ... }
- Catching exceptions: Use try-catch blocks to handle and possibly recover from errors:
try { var user = GetUser(-5); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine...