C
C#14mo ago
Florian Voß

❔ 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?
35 Replies
ero
ero14mo ago
i'd recommend staying away from "handling" exceptions. if you're working with a third library, then it might be difficult to discern what may or may not be thrown without looking at the source code. but i would personally always try and work around potential failures
Florian Voß
Florian Voß14mo ago
and how to do it properly, example given for this method:
public async Task<List<TicketDTO>> GetProblemTicketsAsync()
{
_accessToken = await GetOrCreateAccessTokenAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Authorization", _accessToken.RawToken);
request.Headers.Add("Accept-Language", "en-US");
var response = await _client.SendAsync(request);
if(response.IsSuccessStatusCode)
{
var tickets = await response.Content.ReadFromJsonAsync<List<TicketDTO>>();
return tickets;
}
return null;
}
public async Task<List<TicketDTO>> GetProblemTicketsAsync()
{
_accessToken = await GetOrCreateAccessTokenAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Authorization", _accessToken.RawToken);
request.Headers.Add("Accept-Language", "en-US");
var response = await _client.SendAsync(request);
if(response.IsSuccessStatusCode)
{
var tickets = await response.Content.ReadFromJsonAsync<List<TicketDTO>>();
return tickets;
}
return null;
}
does this method lack exception handling for example or is it fine to not have exception handling? How would it be done properly?
ero
ero14mo ago
for calling a web api, that could mean returning some kind of Result type
Florian Voß
Florian Voß14mo ago
that sounds like great solution Result could carry success and failure. if we wanna keep more simple, is also fine to return null for failure and actual result for success?
ero
ero14mo ago
i think returning null doesn't necessarily mean failure the web api you called could have returned a json with the literal value
null
null
meaning the status is success but null was still returned
Florian Voß
Florian Voß14mo ago
fair but I don't see value in distinguishing this if we don't really handle the exception by sending another request or smth like that
ero
ero14mo ago
what exception? there would be no exception if null was returned by the api
Florian Voß
Florian Voß14mo ago
right I was thinking of null being returned as the representation of an exception happening
ero
ero14mo ago
that's the thing there's null and failure, but there is also null and success both exist
Florian Voß
Florian Voß14mo ago
yeah but then this
ero
ero14mo ago
i don't understand that message
Florian Voß
Florian Voß14mo ago
what's the purpose between distinguishing null and success, and null and failure, how would that change how we keep working?
ero
ero14mo ago
well i can't answer that for you for example for logging purposes
Florian Voß
Florian Voß14mo ago
ah
ero
ero14mo ago
Web request failed! vs. Web request succeeded, but 'null' was returned!
Chiyoko_S
Chiyoko_S14mo ago
exceptions are truly for unexpected cases when you expect errors to happen as part of the normal usage, then it shouldn't be an exception let's say web requests for example. There's an endpoint that takes a POST request including a name, and returns the found object user enters a name. It might not exist and return 404 Not Found it is an error, but it is an 'expected' error at which point we can return null as a way to tell that "we failed to find it but it always could have failed so it's not really an exceptional case" now imagine the datacentre housing the server is on fire and therefore you cannot establish connection with the server in the first place this is an exceptional case you normally aren't supposed to see this happening, and there's nothing we really can do so we just burn everything down but now there are cases where you might have a thing to do if such things happen like try connecting to an alternative server located elsewhere then you could try handling the exception or you might want to perhaps log things down if unexpected exceptions do happen Parse and TryParse is something similar as well. If one knows that the input might not be valid, they'd use the latter it adds a bit more code for error handling, sure, but you want that error handling because you know it can fail but what if you are sure it is a number and is not supposed to fail no point having the error handling code with exceptions, even without those error handling codes that you won't need 99% of the time, you get some free information about where & how it failed if it fails Java has a thing called 'checked exception' which is an exception that must be handled by the callee because it is a trivial error that is likely to happen with the given input. It is criticised for hurting productivity
d1ag0n
d1ag0n14mo ago
forced goto
Chiyoko_S
Chiyoko_S14mo ago
lol
d1ag0n
d1ag0n14mo ago
I have exception handling in my code. Some of it is in a loop so I can check the exception erro code for sql for example I will retry things that have certain error codes. Some exception handlers log. It all depends what you need.
Florian Voß
Florian Voß14mo ago
The only thin I could do here if the api server is burning is request same server again until successful response, should I do that? I don’t have alternative server to use. But then I’d probably just do While(!response.IsSuccess) instead of using a Try catch 🤔
Chiyoko_S
Chiyoko_S14mo ago
there is no point retrying when there is no hopes of recovering
Florian Voß
Florian Voß14mo ago
About logging. I have global exception logging which logs every uncaufht exception to Azure App Insights
Chiyoko_S
Chiyoko_S14mo ago
HttpClient throws for network errors
Florian Voß
Florian Voß14mo ago
But we don’t know if it’s burning, maybe there is hope
Chiyoko_S
Chiyoko_S14mo ago
yes so you might try 10 times or so but what if it still doesn't work
Florian Voß
Florian Voß14mo ago
Mhm I actually run this request every 10 seconds anyway during whole lifetime of my wpf app to update the UI.
Chiyoko_S
Chiyoko_S14mo ago
it's the same reason as why we don't prepare for an ailen invasion. yes, it might happen, but is there any point preparing for it given the unlikeliness & hopes of survival after that that 'ailen invasion' is equivalent to exceptions at least, for normal people like us, that is for militaries and other organisations they might want to actually plan for it which is what try-catch is for edge cases exist, but it becomes very cumbersome to be prepared for every single edge cases that may happen in a huge program at all time and is likely to remain unused even if we do so because again edge cases
Florian Voß
Florian Voß14mo ago
I think I understand, thx a lot Btw is this fine? I know real-time app would be better but I don’t think it’s possible because the external api I request is not under my control. So sending restful request from wpf app every 10 seconds seems fine right? @not Aoba Need to update Tickets in for tech support in wpf UI
Chiyoko_S
Chiyoko_S14mo ago
it all depends I guess. Though it might be better if thet have a way to notify us when it happens instead of constantly needing to query about it webhooks or something similar RE: exception - for an UI app I definitely wouldn't want to crash the app because a network request failed it all depends!
Florian Voß
Florian Voß14mo ago
That would be awesome but I have no clue how. I only know restful http communication but not real-time http connection. I think that would require websocket connection? Me noob
Chiyoko_S
Chiyoko_S14mo ago
kekw
Florian Voß
Florian Voß14mo ago
Ah we in same boat 🛥
Chiyoko_S
Chiyoko_S14mo ago
that's the part about the exception anyway
Florian Voß
Florian Voß14mo ago
Yeah thx a lot for that ❤️
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.