Some Quick and Easy Exception Handling (Using Try-Catch Statements)
This is just a quick article about a bit of exception handling we can do when programming š Admittedly, thereās a time and a place for just doing some null checks but sometimes youāll want the program to intervene a little more when somethingās not quite right. A try-catch statement containing a methodās code can offer just this:
This sort of usage will let us know where an error occurred (or, at least, the method it occurred in), and any information contained within the exception we catch.
If your method is on the large side, you may well want to isolate this further, and youāre welcome to do some exception-handling nesting such as this:
You donāt need some of this āException eā stuff if youāre not interested in printing out the error information; you can just use these nested try-catch statements to catch exceptions without the entire methodās try-catch statement from triggering. Some standard null-checking can also do the trick with this:
Lastly, something this got me thinking about is considering whatās most appropriate for the situation. Iām sometimes wondering whether itās more important for the program to do its best to continue in spite of an exception or whether itās better for it to essentially stop the program before it can do any damage. I appreciate the latter might be the more correct answer, but realistically I do feel there are going to be plenty of occasions where you simply need things to hold together for the user experience (unglamorous as that sounds). Of course in an ideal world nothing will go wrong with your program and everything will work just fine, but since this isnāt that world it feels important to prepare for the worst.
Some of this comes to mind as a result of some programming Iām doing and working with at the moment, which ends up going onto essentially a number of microcontrollers. These really canāt handle exceptions themselves, and they may well need replacing or repairs if your code is sufficiently faulty. In these cases, I feel I can more safely say that I want the program to stop what itās doing in the event of an exception rather than continue š But anyway, I hope thatās some food-for-thought.