Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Note: For more information, refer to Errors and Exceptions in Python
Some of the common Exception Errors are :
- IOError: if the file can’t be opened
- KeyboardInterrupt: when an unrequired key is pressed by the user
- ValueError: when the built-in function receives a wrong argument
- EOFError: if End-Of-File is hit without reading any data
- ImportError: if it is unable to find the module
Try Except in Python
Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
How try() works?
- First, the try clause is executed i.e. the code between try.
- If there is no exception, then only the try clause will run, except clause is finished.
- If any exception occurs, the try clause will be skipped and except clause will run.
- If any exception occurs, but the