160 likes | 170 Views
Learn to manage errors efficiently with return codes, setjmp/longjmp, exceptions, and prevent resource leaks. Explore useful functions and best practices for logging, debugging, and preventing security risks. Keep your code clean and robust.
E N D
Errors and Exceptions Chapter 8
Overview • Handling errors • With return values. • With setjmp/longjmp. • With exceptions. • Preventing resource leaks. • Logging and debugging.
Handling errors with return codes. • Simple idea but: • Makes it easy to ignore errors • The code becomes harder to read, write and understand. • There is no universal convention for communicating error information.
Useful C Functions for handling errors • errno • perror • strerror • error and friends • err/warn • setjmp/longjmp
Exceptions in C++ • Mechanism: • try{....}catch(....){...}catch(...){...}... • First sequence of code is code to execute. • This code can “throw” exceptions which are “caught” by the apprpriate catch phrase.
Managing exceptions • Exceptions in java vs C++ (checked or unchecked) • Not catching an exception will cause a program crash, -> DOS attack. • At least, catch everything at top level to avoid “spilling beans”. • Deeper down, catch only what you can handle. • Watch for “finally” clauses in Microsoft C++/Java (pp 273/274)
Preventing Resource Leaks • Only real security risk is DOS, but can cause serious performance problems. • Very hard to track down and identify. • Usually manifest themselves only in production • Very hard to trace back to their origin. • Usually due to seldom traversed instruction paths, like error or exception handlers.
Logging and Debugging • Centralize the output operation. There are packages for this. • Provide a uniform view. • Make it easier to change medium, machine, etc. • Provide time stamps. • Log every important action, including failures! • Protect the logs.
A few final words • Keep debugging aids out of production • Keep back-door access code out of production • Clean out Backup files • Say “NO” to Easter Eggs.
Resource leaks “gotchas” • Watch for multiple return statements • In C++, classes can be used to advantage, but watch out for strange modifications.