Exceptions are raised when the program is syntactically correct, but the code result in an error. This error doesn't stop the execution of the program. It changes the normal flow of the program.
Types of Exceptions in Python:
TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer.
NameError: This exception is raised when a variable or function name is not found in the current scope.
IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called with an invalid argument or input, such as trying to convert a string to an integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to access a non-existent attribute of a class instance.
IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
ImportError: This exception is raised when an import statement fails to find or load a module.
Exception vs syntax error:
Errors are 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 change the normal flow of the program.
Two types of Errors occur in Python.
- Syntax errors
- Logical errors (Exceptions)
a=[1,2,3]
a[3]
IndexError: list index out of range
The above code is syntactically correct but still, it throws an error. Instead of displaying "Exception Error", python display information about the exception error.
Try and Except Statement:
Try clause contains the code that can raise an exception, while the exception clause contains the line that handles the exception.
Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
a=[1,2,3]
try:
print(a[3])
except:
print('an error occured')
How to raise an exception:
If a condition does not meet our criteria but is correct according to the Python interpreter, we can intentionally raise an exception using the raise keyword.
Catching specific Exception:
except IndexError:
a=[1,2,3]
try:
print(a[3])
except IndexError:
print('an error occured')
a=[1,2,3]
try:
print(b[3])
except IndexError:
print('an error occured')
Try with Else Clause
Python also supports the else clause, which should come after every except clause, in the try, and except blocks.
Only when the try clause fails to throw an exception the Python interpreter goes on to the else block.
a=[1,2,3]
try:
print(a[1])
except IndexError:
print('an error occured')
else:
print('no exception')
Finally Keyword
Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Even if you return in the except block still the finally block will execute.
a=[1,2,3]
try:
print(a[6])
except IndexError:
print('an error occured')
else:
print('no exception')
finally:
print('hjkk')