In Error and Exception Handling we use try() and except() functions to deal with erros, especially in python for data science.
Errors are of two types:
- Syntax Error: This error is there when the Python parser does not understand a line of code. It is also known as Parsing Error.
- Exception: These are the errors that are detect during execution. One such example of Exception is ZeroDivisionError.
Some of the Exception Errors:
- IOError: If the file cannot be opened, this error will be generated.
- KeyboardInterrupt: This error occurs in case the user presses an un-required key.
- ValueError: This error comes into picture in case a built-in function receives a wrong argument.
- EOFError: This error is generate in a situation where End of File hits without any data being read.
- ImportError: This error will be generate in case the module is not found.
Now we will look at the Syntax for try-except.
Working of try():
- First of all, the try() clause i.e., the code between try and clause is executed.
- In case of no exceptions, only try clause is executed, and except clause is finished.
- And in case an exception occurs except clause will be run and try clause is skipped.
- In case an exception occurs, but the except clause which is in the code does not handle it, it is passed to the outer try statement. If any chance the exception is not handled, the execution will stop.
- A try statement might have more than one except statement.
Code 1: No exception is present so, try clause is executed.
Code 2: In this code, there is an exception so, except clause will run.