Some Quick and Easy Exception Handling (Using Try-Catch Statements)

Marcus Ansley
3 min readSep 25, 2021

--

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.

--

--

Marcus Ansley
Marcus Ansley

Written by Marcus Ansley

Game Developer | Game Design and Literature Graduate

No responses yet