C#C
C#3y ago
Thalnos

❔ Exception Handling

I have a rather general issue with understanding exceeption handling. I've learned that we usually wanna do exception handling when working with external ressources as we don't know what may fail in that case.
A common use case for exception handling would be calling an api right?

But as we all know exception handling is only for, well - exceptional state. How could an api call run into exceptional state? It is to be expected that we might not get a successful response. So do we even want to have exception handling when calling an api?

Would it be safe enough to only check for a successful response and to return null otherwise?

I don't even know what we would do in a case when we catch an exception here, keep sending the request until it's successful or how would that be handled? I feel like that could be done without a try catch.

Another common case for exception handling would be any I/O operations such as writing to a file tho. But again, I don't understand how that could run into exceptional state? Isn't something like a DirectoryNotFoundException and stuff something that's to be expected?

I guess it all comes down to this - The moment that we start writing a try-catch, we do expect an Exception to be thrown, but exception handling is for unexpected situations. That seems contradicting to me.

When do we want exception handling and when don't we want exception handling?
Was this page helpful?