| ||
The only real redemption steps are as follows :
Handle the appropriate exceptions in your code.
Dont gobble exceptions.
Make sure you check return values when appropriate.
In the code that follows, rather than check just a bunch of asserts, were going to check all arguments coming into the code, and then handle the return from fopen appropriately.
The guideline for using asserts is they should only check for conditions that should never happen.
DWORD OpenFileContents(char *szFilename) { if (szFilename == NULL strlen(szFilename) <= 3) return ERROR_BAD_ARGUMENTS; FILE *f = fopen(szFilename,"r"); if (f == NULL) return ERROR_FILE_NOT_FOUND; // Do work on the file return 1;
Microsoft Visual Studio .NET 2005 includes a technology named Source code Annotation Language (SAL) to help detect, amongst many other errors, return issues. When its compiled, the following code issues this warning:
Warning C6031: return value ignored: ˜Function could return unexpected value.
__checkReturn DWORD Function(char *szFilename) { DWORD dwErr = NO_ERROR; // Do work return dwErr; } void main() { Function("c:\junk\1.txt"); }
This pseudo-code handles only the errors it knows about, and no more.
try { // (1) Load an XML file from disc // (2) Use some data in the XML to get a URI // (3) Open the client certificate store to get a // client X.509 certificate and private key // (4) Make an authenticated request to the sever described in (2) // using the cert/key from (3) } catch (SecurityException e1) { // handle security errors } catch (XmlException e2) { // handle XML errors } catch (IOException e3) { // handle I/O errors } catch (FileNotFoundException e4) { // handle File errors } catch (SocketException e4) { // handle socket comms errors }