2 Handling exceptions
- Exception vs error: errors cannot be handled, while exceptions can be catched at the run time. The error indicates a problem that mainly occurs due to the lack of system resources while Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers. An error can be a syntax error, while there can be many types of exceptions that could occur during the execution. An error might indicate critical problems that a reasonable application should not try to catch, while an exception might indicate conditions that an application should try to cacth.
Note
Python uses float because with binary representation we can’t represent decimal numbers. Every number is actually some approximation of some other number, and difference between representation and real value is called round-off error.
- Try-except-else: the try block lets you test a block of code for errors. The except block gets executed when the error occurs. The else block lets you execute code when there is no error.
- Try-except-finally: finally statement is opposite of „else“. It always executes after try and except blocks. It is used to do the clean up activities of objects/variables.