12.exception
12.exception
E:\python>python e.py
second element 2
Traceback (most recent call last):
File "E:\python\e.py", line 4, in <module>
print("third element ",a[3])
~^^^
IndexError: list index out of range
Try and Except Statement – Catching Exceptions
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:
E:\python>python e.py
print("third element An error occured
",a[3]) outside try-except
except:
print("An error occured")
print("outside try-except")
Handling Exceptions
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for
different exceptions. At most one handler will be executed. For example, we can add
IndexError in the above code. The general syntax for adding specific exceptions are –
a=[1,2,3]
try:
print("third element ",a[3])
except IndexError:
print("An index error occured check ur code")
except:
print("An error occured")
print("outside try-except")
E:\python>python e.py
An index error occured check ur code
outside try-except
Try-except block
try: the code with the exception(s) to catch. If an exception is
raised, it jumps straight into the except block.
except: this code is only executed if an exception occured in
the try block. The except block is required with a try block,
even if it contains only the pass statement.
else: Code in the else block is only executed if no exceptions
were raised in the try block.
finally: The code in the finally block is always executed,
regardless of if an exception was raised or not.
Try-except-else-finally
Type error
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.
ValueError
Python ValueError is raised when a function receives an argument of the correct
type but an inappropriate value.
ValueError
Python ValueError is raised when a function receives an argument of the correct
type but an inappropriate value.
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.
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.