Try Catch Exception Handling
BlitzMax Forums/BlitzMax Programming/Try Catch Exception Handling
| ||
Just want to know if exception handling is common usage? I've never used it before and was wondering if in professional software projects exception handling is ideal? |
| ||
Yes, it is ideal. I would recommend it to use it in the main function call at last, so if an exception is unhandled in the regular program usage, you can always use this to display infomation about the error to the user, inform the the application is going to be closed, etc. This ismuch better than letting the app just end without any more info. EDIT: Forgot to mention that tyr/catch sometimes does not work as expected on release mode. Not sure why... (and not sure it's a bug). |
| ||
I tried it before but couldn't get it to work properly. null object errors started to become ignored entirely!! |
| ||
Type SomeExceptionType 'define your exception type Method ToString$() 'Message going to appear in debugger Return "Message" End End Type Try ... If SomethingBadHappens() Then Throw new SomeExceptionType ... Catch ex:SomeExceptionType 'This is the correct way to do, it only catches exceptions of SomeExceptionType ... Catch ex:SomeOtherExceptionType Catch ex:Object 'Never use this, it catches system exceptions ... End Try Try...Catch only makes sense when you're dealing with known exceptions. You have to throw those exceptions by yourself. Null Object is not an exception but an error, it's not something for Try...Catch to handle. *EDIT: You can also catch exceptions defined in other modules, like TStreamException. It's a nice tool to organize the code structure. You can use it to take exception handling out of actual implementation. |
| ||
I implement it any time there's file access that may not be perfect. e.g. loading a saved file. The stream may report it is as long as you expect, but in actuality be shorter, so when you try to read all your data back it hits a wall, throws an exception and crashes. If you just catch that exception you can tell the user the file they want is damaged and then continue about your business. If your saves are at all slow (lots of processing done during the save for example) you're bound to create a bad file here or there when a user gets their hands on it (people like to force quit more than you'd think, especially when the app reports it's not responding due to no time in the main loop to process events). Working around potential problems is a big part of programming, one that often gets over looked via the "it works here it must work everywhere" mentality of rapid development. |