❔ Exception Handling question
IF i Want to add exception handling to all of my program, do I have to put all of the code into the try{} block?
8 Replies
I've always had that question as well. I think you can create a middleware to handle all exceptions, but I'm not entirely sure what kind of logic would start using this middleware
Middleware only applies in certain environments
Your entry point code can handle an exception at the root either prior to exit or restart
Such as
📅 do you remember?
REPL Result: Success
Console Output
Compile: 616.336ms | Execution: 90.183ms | React with ❌ to remove this embed.
it depends on the strategy how you want to deal with exceptions
lets say you put one giant try catch around your program. what do you think will happen if an exception is thrown?
spoiler:
you will catch the exception and then the application closes (as long you dont program anything that restarts the app or so)
there is middleware for stuff like aspnet but more generally there is unhandledexceptionhandler in the appdomain
also just my 2 cents, try catches should in general only used where you have no full control like IO and exceptions can just happen. in all other cases your code should be improved so that you cant even get an exception, eg checking for null etc. bad code causes exceptions and should be treated as bugs
also to expand.. try catches are there to get from an undefined state to defined state again by eg. rolling changes back or discard data. so the normal operation of the application can continue
I see
Would it be better if I tried to prevent the said exception from happening, or like, work around it?
For example if someone enters a number instead of a word, I check if it's a number and if it is, it reverts then back to the writing prompt?
Preventing it from happening in the first place is better. Your example is great but wouldn't necessarily cause an exception, if we flip it around, it better demonstrates the concept:
Take a
NullReferenceException
which is easy to guard against but often neglected:
Hope this helps 🙂Helps a ton, thank you all <:BL_PepeHeart:1142846257916809228>
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.