In any programming language, there are 2 types of errors that are possible.
- Syntax Errors
- Runtime Errors
1. Syntax Errors:
The errors which occurs because of invalid syntax are called syntax errors.
Eg 1:
x=10 if x==10 print("Hello")
SyntaxError: invalid syntax
Eg 2:
print "Hello"
SyntaxError: Missing parentheses in call to 'print'
2. Runtime Errors:
Also known as exceptions.
While executing the program if something goes wrong because of end user input or
programming logic or memory problems etc then we will get Runtime Errors.
Eg: print(10/0) ==>ZeroDivisionError: division by zero
print(10/"ten") ==>TypeError: unsupported operand type(s) for /: 'int' and 'str'
x=int(input("Enter Number:"))
print(x)
D:\Python_classes>py test.py
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'
What is Exception:
An unwanted and unexpected event that disturbs normal flow of program is called
exception.
Eg:
ZeroDivisionError TypeError ValueError FileNotFoundError EOFError SleepingError TyrePuncturedError
It is highly recommended to handle exceptions. The main objective of exception handling
is Graceful Termination of the program(i.e we should not block our resources and we
should not miss anything)
Exception handling does not mean repairing exception. We have to define alternative way
to continue rest of the program normally.
try:
read data from remote file locating at london
except FileNotFoundError:
use local file and continue rest of the program normally
Q. What is an Exception?
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?
Default Exception Handing in Python:
Every exception in Python is an object. For every exception type the corresponding classes are available.
Whevever an exception occurs PVM will create the corresponding exception object and will check for handling code. If handling code is not available then Python interpreter terminates the program abnormally and prints corresponding exception information to the console.
The rest of the program won't be executed.
Eg:
1) print("Hello") 2) print(10/0) 3) print("Hi") 4) 5) D:\Python_classes>py test.py 6) Hello 7) Traceback (most recent call last): 8) File "test.py", line 2, in <module> 9) print(10/0) 10) ZeroDivisionError: division by zero
img:207
Every Exception in Python is a class.
All exception classes are child classes of BaseException.i.e every exception class extends BaseException either directly or indirectly. Hence BaseException acts as root for Python Exception Hierarchy.
Most of the times being a programmer we have to concentrate Exception and its child classes.
Customized Exception Handling by using try-except:
It is highly recommended to handle exceptions.
The code which may raise exception is called risky code and we have to take risky code inside try block. The corresponding handling code we have to take inside except block.
try:
Risky Code
except XXX:
Handling code/Alternative Code
with try-except:
1. print("stmt-1") 2. try: 3. print(10/0) 4. except ZeroDivisionError: 5. print(10/2) 6. print("stmt-3") 7. 8. Output 9. stmt-1 10. 5.0 11. stmt-3
Normal termination/Graceful Termination
Control Flow in try-except:
try: stmt-1 stmt-2 stmt-3 except XXX: stmt-4 stmt-5
case-1: If there is no exception
1,2,3,5 and Normal Termination
case-2: If an exception raised at stmt-2 and corresponding except block matched
1,4,5 Normal Termination
case-3: If an exception raised at stmt-2 and corresponding except block not matched
1, Abnormal Termination
case-4: If an exception raised at stmt-4 or at stmt-5 then it is always abnormal termination.
How to print exception information:
try:
1. print(10/0) 2. except ZeroDivisionError as msg: 3. print("exception raised and its description is:",msg) 4. 5. Output exception raised and its description is: division by zero
try with multiple except blocks:
The way of handling exception is varied from exception to exception. Hence for every exception type a seperate except block we have to provide. i.e try with multiple except blocks is possible and recommended to use.
Eg:
try: ------- ------- ------- except ZeroDivisionError: perform alternative arithmetic operations except FileNotFoundError: use local file instead of remote file
Single except block that can handle multiple exceptions:
We can write a single except block that can handle multiple different types of exceptions.
except (Exception1,Exception2,exception3,..): or except (Exception1,Exception2,exception3,..) as msg :
Parenthesis are mandatory and this group of exceptions internally considered as tuple.
Eg:
1) try: 2) x=int(input("Enter First Number: ")) 3) y=int(input("Enter Second Number: ")) 4) print(x/y) 5) except (ZeroDivisionError,ValueError) as msg: 6) print("Plz Provide valid numbers only and problem is: ",msg) 7) 8) D:\Python_classes>py test.py 9) Enter First Number: 10 10) Enter Second Number: 0 11) Plz Provide valid numbers only and problem is: division by zero 12) 13) D:\Python_classes>py test.py 14) Enter First Number: 10 15) Enter Second Number: ten 16) Plz Provide valid numbers only and problem is: invalid literal for int() with b 17) ase 10: 'ten'
Default except block:
We can use default except block to handle any type of exceptions.
In default except block generally we can print normal error messages.
Syntax: except: statements
Eg:
1) try: 2) x=int(input("Enter First Number: ")) 3) y=int(input("Enter Second Number: ")) 4) print(x/y) 5) except ZeroDivisionError: 6) print("ZeroDivisionError:Can't divide with zero") 7) except: 8) print("Default Except:Plz provide valid input only") 9) 10) D:\Python_classes>py test.py 11) Enter First Number: 10 12) Enter Second Number: 0 13) ZeroDivisionError:Can't divide with zero 14) 15) D:\Python_classes>py test.py 16) Enter First Number: 10 17) Enter Second Number: ten 18) Default Except:Plz provide valid input only
finally block:
1. It is not recommended to maintain clean up code(Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarentee for the execution of every statement inside try block always.
2. It is not recommended to maintain clean up code inside except block, because if there is no exception then except block won't be executed.
Hence the main purpose of finally block is to maintain clean up code.
try: Risky Code except: Handling Code finally: Cleanup code
Various possible combinations of try-except-else-finally:
1. Whenever we are writing try block, compulsory we should write except or finally block.i.e without except or finally block we cannot write try block.
2. Wheneever we are writing except block, compulsory we should write try block. i.e except without try is always invalid.
3. Whenever we are writing finally block, compulsory we should write try block. i.e finally without try is always invalid.
4. We can write multiple except blocks for the same try,but we cannot write multiple finally blocks for the same try
5. Whenever we are writing else block compulsory except block should be there. i.e without except we cannot write else block.
6. In try-except-else-finally order is important.
7. We can define try-except-else-finally inside try,except,else and finally blocks. i.e nesting of try-except-else-finally is always possible
Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Definded Exceptions
1. Predefined Exceptions:
Also known as in-built exceptions
The exceptions which are raised automatically by Python virtual machine whenver a particular event occurs, are called pre defined exceptions.
Eg 1: Whenever we are trying to perform Division by zero, automatically Python will raise
ZeroDivisionError.
print(10/0)
Eg 2: Whenever we are trying to convert input value to int type and if input value is not int value then Python will raise ValueError automatically
x=int("ten")===>ValueError
2. User Defined Exceptions:
Also known as Customized Exceptions or Programatic Exceptions
Some time we have to define and raise exceptions explicitly to indicate that something goes wrong ,such type of exceptions are called User Defined Exceptions or Customized Exceptions
Programmer is responsible to define these exceptions and Python not having any idea about these. Hence we have to raise explicitly based on our requirement by using "raise" keyword.
Eg:
InSufficientFundsException InvalidInputException TooYoungException TooOldException
How to Define and Raise Customized Exceptions:
Every exception in Python is a class that extends Exception class either directly or indirectly.
Syntax:
class classname(predefined exception class name): def __init__(self,arg): self.msg=arg
Eg:
1) class TooYoungException(Exception): 2) def __init__(self,arg): 3) self.msg=arg
"Python Exception Handling"
"Python Exception Handling
Examples"
"Python Exception Handling
Programs"
"Python Exception Handling
Exercises"
"Python Exception Handling
Decorator"
"Raise In Python Exception
Handling"
"Requests Python Exception
Handling"
"When To Use Python Exception
Handling"
"Python Multiple Exception
Handling"
"Python Requests Exception
Handling"
"Python File Exception Handling"