Generally we will
get the two types of errors in any programming
Language. They are:
- Syntax Error
- Run time Error
Syntax Error
- The errors which occurs because of syntax mistakes are known as syntax errors.
- If any syntax errors are there in our Python program then program execution will not be started.
- Python programmers and developers are responsible for providing the solutions to the syntax error.
>>> def f2( ):
print("hai")
SyntaxError: expected an indented block
Run time error:
The errors which
occurs after starting the execution of the program are known as run time errors.
Generally we will
get the run time errors because of
- invalid data.
- Program logic
- Memory related issues
- Hardware failures ....... etc
- With respect to every run time error corresponding run time error representation class is available.
- Run time error representation classes technically we call as Exception classes.
- While executing the program if any run time error is occurred then automatically corresponding run time error representation class object will be created. Creating run time error representation class object is technically known as a raising exception.
- If the Python program doesn't contain any code to handle the raised exception then program is going to terminate abnormally.
x=int(input("enter integer value:"))
enter integer value:2.5
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
x=int(input("enter integer value:"))
ValueError: invalid literal for int() with base 10: '2.5'
Abnormal Termination
- Concept of terminating the program in the middle of its execution without executing the last statement of the program is known as abnormal termination.
- Abnormal termination is the undesirable situation in any programming Language.
print("begin")
x=int(input("enter fno: "))
y=int(input("enter sno: "))
x=x/y
print(x)
print("end")
begin
enter fno: 4
enter sno: 0
Traceback (most recent call last):
File "E:/python_practice/examples/exception1.py", line 4, in <module>
x=x/y
ZeroDivisionError: division by zero
Exception Handling:
- The concept of identifying which run time error representation class object is created, receiving that object and assigning that object to corresponding run time error representation class is known as Exception Handling.
- We can implement exception handling in Python by using try and except blocks.
try block:-
- A block which is preceded by the try keyword is known as a try block.
try block syntax
try:
statement1
statement2
.
.
.
statement_n
- The statements which causes to run time errors and other statements which depends on the execution of run time error occurred statements are recommended to represent in try block
- While executing the try block if any run time error is occurred then immediately that run time error represented class object is identified, received by the try block and forward that object to except block without executing remaining statements of the try block
except block:
- A block which is preceded by except keyword is known as except block.
Default Except
block syntax:-
except:
statement1
statement2
.
.
.
statement_n
print("begin")
x=int(input("enter fno: "))
y=int(input("enter sno: "))
try:
z=x/y
print(z)
except:
print("sno cannot be zero")
print("end")
begin
enter fno: 1
enter sno: 2
0.5
end
begin
enter fno: 1
enter sno: 0
sno cannot be zero
end
Note:
- Default Except block can handle any type of Exception.
Named Except block
syntax:-
except(RuntimeErrorRepresentationClass):
statement1
statement2
.
.
.
statement_n
print("begin")
x=int(input("enter fno: "))
y=int(input("enter sno: "))
try:
z=x/y
print(z)
except(ZeroDivisionError):
print("sno cannot be zero")
print("end")
begin
enter fno: 1
enter sno: 2
0.5
end
begin
enter fno: 1
enter sno: 0
sno cannot be zero
end
y=input("enter y value:")
try:
z=x/int(y)
print(z)
except ValueError:
print("enter correct value")
except ZeroDivisionError:
print("sno cannot be zero")
except:
print("hai")
Note:
- Named Except block can handle particular type of Exception only
- Except block receives the run time error representation class objects which is given by the try block and assign that object to the corresponding run time error representation class.
- While executing the try block statements if exception is raised then only control will go to the except block.
- In except block we can define the statements to display the user friendly error messages.
Simple try with multiple except blocks:
- It is recommended to handle the different exceptions by using the different except blocks to display the corresponding user friendly error messages.
- Whenever we define single try with multiple except blocks, if exception is raised in the try block then control will go to first except block.
- If first except block is not handled that exception then control will go to second except block and so on.
x=int(input("enter fno: "))
y=int(input("enter sno: "))
try:
z=x/y
print(z)
except(NameError):
print("enter numerical value only")
except(ZeroDivisionError):
print("sno cannot be zero")
except:
print("error occurred")
print("end")
begin
enter fno: 1
enter sno: 2
0.5
end
begin
enter fno: 1
enter sno: 0
sno cannot be zero
end
Note:
enter fno: 1
enter sno: 2
0.5
end
begin
enter fno: 1
enter sno: 0
sno cannot be zero
end
Note:
- Default except block must be the last block otherwise it gives error
print("begin")
x=int(input("enter fno: "))
y=int(input("enter sno: "))
try:
z=x/y
print(z)
except:
print("error occurred")
except(ValueError):
print("enter number is value only")
except(ZeroDivisionError):
print("sno cannot be zero")
print("end")
finally block:-
- A block which is preceded by the finally keyword is known as finally block.
syntax:
finally:
statement1
statement2
.
.
.
statement_n
- The set of statements which must be execute whether exception is raised or not raised, even though exception is raised whether it is handled or not handled are recommended to write in finally block.
- Resource releasing statements(file closing statements, database connection closing statements) are recommended to write in finally block.
type1:
try:
-----------------
-----------------
-----------------
finally:
-----------------
-----------------
-----------------
type2:
try:
-----------------
-----------------
-----------------
except:
-----------------
-----------------
-----------------
finally:
-----------------
-----------------
-----------------
print("begin")
x=int(input("enter fno: "))
y=int(input("enter sno: "))
try:
z=x/y
print(z)
except(ZeroDivisionError):
print("sno cannot be zero")
finally:
print("in finally block")
print("end")
begin
enter fno: 1
enter sno: 2
0.5
in finally block
end
begin
enter fno: 1
enter sno: 0
sno cannot be zero
in finally block
Nested
try-except-finally block:
- We can define the one try block inside another try block.
- A try block which contains another try block is known as a outer try block.
- A try block which is defined in another try block is known as inner try block.
- If exception is raised in the outer try block that can be handled only by using outer try except block.
- If exception is raised in the inner try block that can be handled using inner try-except block, if inner try-except block is not handled then we can also handle using outer try-except block.
try:
print("In outer try")
try:
print("In inner try")
except:
print("In inner except")
finally:
print("In inner finally")
except:
print("In outer except")
try:
print("In try of except")
except:
print("In except of except")
finally:
print("In finally of except")
finally:
print("In outer finally")
try:
print("In try of finally")
except:
print("In except of finally")
finally:
print("In finally of finally")
In outer try
In inner try
In inner finally
In outer finally
In try of finally
In finally of finally
Python
Built-in Exceptions
|
|
Exception
|
Cause of Error
|
AssertionError
|
Raised when assert statement
fails.
|
AttributeError
|
Raised when attribute assignment or reference fails.
|
EOFError
|
Raised when the input() functions
hits end-of-file condition.
|
FloatingPointError
|
Raised when a floating point operation fails.
|
GeneratorExit
|
Raise when a generator's close()method is called.
|
ImportError
|
Raised when the imported module is not found.
|
IndexError
|
Raised when index of a sequence is out of range.
|
KeyError
|
Raised when a key is not found in a dictionary.
|
KeyboardInterrupt
|
Raised when the user hits interrupt key (Ctrl+c or
delete).
|
MemoryError
|
Raised when an operation runs out of memory.
|
NameError
|
Raised when a variable is not found in local or global
scope.
|
NotImplementedError
|
Raised by abstract methods.
|
OSError
|
Raised when system operation causes system related
error.
|
OverflowError
|
Raised when result of an arithmetic operation is too
large to be represented.
|
ReferenceError
|
Raised when a weak reference proxy is used to access a
garbage collected referent.
|
RuntimeError
|
Raised when an error does not fall under any other
category.
|
StopIteration
|
Raised by next() function to indicate that
there is no further item to be returned by iterator.
|
SyntaxError
|
Raised by parser when syntax error is encountered.
|
IndentationError
|
Raised when there is incorrect indentation.
|
TabError
|
Raised when indentation consists of inconsistent tabs
and spaces.
|
SystemError
|
Raised when interpreter detects internal error.
|
SystemExit
|
Raised by sys.exit() function.
|
TypeError
|
Raised when a function or operation is applied to an
object of incorrect type.
|
UnboundLocalError
|
Raised when a reference is made to a local variable in a
function or method, but no value has been bound to that variable.
|
UnicodeError
|
Raised when a Unicode-related encoding or decoding error
occurs.
|
UnicodeEncodeError
|
Raised when a Unicode-related error occurs during
encoding.
|
UnicodeDecodeError
|
Raised when a Unicode-related error occurs during
decoding.
|
UnicodeTranslateError
|
Raised when a Unicode-related error occurs during
translating.
|
ValueError
|
Raised when a function gets argument of correct type but
improper value.
|
ZeroDivisionError
|
Raised when second operand of division or modulo
operation is zero.
|
User defined Exceptions:
- The exception classes which are defined by the programmers according to their business requirements are known as user defined Exceptions.
Steps to implement user defined Exceptions:-
1).Defining user
defined Exception class:-
- Any user defined class which is extending any one of the pre-defined exception class is known as a user defined Exception class.
Syntax
class <class_name>(Exception):
--------------------------------------------
--------------------------------------------
--------------------------------------------
2).Raising the user
defined Exception explicitly:-
- Creating the exception class objects is technically known as a raising the Exception.
- Pre-defined Exceptions raised automatically whenever corresponding runtime error is occurred.
- We have to raise user defined exceptions explicitly according to our business requirements by using following syntax.
Syntax:
raise <Exception_class_name>
3).Handling the
raised Exceptions:
- We can handle the raised Exceptions by using try and except blocks.
class Error(Exception):
"""Base class for other Exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the value is too long"""
pass
num=10
while True:
try:
i_num=int(input("Enter a number: "))
if i_num<num:
raise ValueTooSmallError
elif i_num>num:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("Too small, Try again")
except ValueTooLargeError:
print("Too long, Try again")
print()
print("Your guess is correct")
Enter a number: 5
Too small, Try again
Enter a number: 12
Too long, Try again
Enter a number: 10
Your guess is correct
No comments:
Post a Comment