IKH

Exception Handling

  • Exception handling does not mean repairing exception. We have to define alternative way to continue rest of the program normally.
  • Every exception in python is an object. For every exception type the corresponding classes are availably. Wherevers an exception occurs PVM will create the corresponding exception object and 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 and rest of the program won’t be executed.
  • There are three keywords in python to handle exception;
    • try
    • except
    • finally
  • There are multiple combination of try, except and finally block to handle exception.

Using try except

  • 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.

Syntax

Python
try:
  # Risky Code
except:
  # Handling Code / Alternative Code

Example

Without try-except

Python
print("stmt-1")
print(10/0)
print("stmt-3")

Output

PowerShell
stmt-1
ZeroDivisionError: division by zero
  • This is the abnormal termination / non-graceful termination.

With try-except

Python
print("stmt-1")
try:
  print(10/0)
except ZeroDivisionError:
  print(10/2)
print("stmt-3")

Output

PowerShell
stmt-1
5.0
stmt-3
  • This is the normal termination / graceful termination.

Control Flow in try-except

Syntax

Python
try:
  stmt-1
  stmt-2
  stmt-3
except XXX:
  stmt-4
stmt-5

Case 1: If there is no exception

PowerShell
stmt-1
stmt-2
stmt-3
stmt-5
  • Normal termination.

Case 2: If an exception raised at stmt-2 and corresponding except block matched

PowerShell
stmt-1
stmt-4
stmt-5
  • Normal termination.

Case -3: If an exception raised at stmt-2 and corresponding except block not matched

PowerShell
stmt-1
  • Abnormal termination.

Case 4: If an exception raised at stmt-4 or at stmt-5

PowerShell
stmt-1
stmt-2
stmt-3
  • Abnormal termination.

Conclusions

  • Within the try block if anywhere exception raised then rest of the try block wont be executed even though we handled that exception. Hence we have to take only risky code inside try block and length of the try block should be as less as possible.
  • In addition to try block there may be a chance of raising exceptions inside except and finally blocks also.
  • If any statement which is not part of try block raises an exception then it is always abnormal termination.

Using try with multiple except

  • The way of handling exception is varied from exception to exception. Hence for every exception type a separate except block we have to provide i.e. try with multiple except blocks is possible and recommended to use.

Syntax

Python
try:
  # Risky Code
except ZeroDivisionError:
  # Handling Code / Alternative Code
except FileNotFoundError:
  # Handling Code / Alternative Code
  • If try with multiple except blocks available then based on raised exception the corresponding except block will be executed

Example

Python
try:
  x=int(input("Enter First Number: "))
  y=int(input("Enter Second Number: "))
  print(x/y)
except ZeroDivisionError:
  print("Can't Divide with Zero")
except ValueError:
  print("please provide int value only")

Output

PowerShell
Enter First Number: 10
Enter Second Number: 2
5.0
PowerShell
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
PowerShell
Enter First Number: 10
Enter Second Number: ten
please provide int value only
  • If try with multiple except blocks available then the order of these except blocks is important. Python interpreter will always consider from top to bottom until matched except block identified.

Example

Python
try:
  x=int(input("Enter First Number: "))
  y=int(input("Enter Second Number: "))
  print(x/y)
except ArithmeticError:
  print("ArithmeticError")
except ZeroDivisionError:
  print("ZeroDivisionError")

Output

PowerShell
Enter First Number: 10
Enter Second Number: 0
ArithmeticError

Single except block that can handle multiple exceptions

  • We can write a single except block that can handle multiple different types of exceptions.

Syntax

Python
except (Exception1,Exception2,exception3,..) as msg:
  # Code for exception handling
  • Parenthesis are mandatory and this group of exceptions internally considered as tuple.

Example

Python
try:
  x=int(input("Enter First Number: "))
  y=int(input("Enter Second Number: "))
  print(x/y)
except (ZeroDivisionError,ValueError) as msg:
  print("Plz Provide valid numbers only and problem is: ",msg)

Output

PowerShell
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is:  division by zero
PowerShell
Enter First Number: 10
Enter Second Number: ten
Plz Provide valid numbers only and problem is:  invalid literal for int() with base 10: 'ten'

Using 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

Python
except:
  # statements

Example

Python
try:
  x=int(input("Enter First Number: "))
  y=int(input("Enter Second Number: "))
  print(x/y)
except ZeroDivisionError:
  print("ZeroDivisionError:Can't divide with zero")
except:
  print("Default Except:Plz provide valid input only")

Output

PowerShell
Enter First Number: 10
Enter Second Number: 0
ZeroDivisionError:Can't divide with zero
PowerShell
Enter First Number: 10
Enter Second Number: ten
Default Except:Plz provide valid input only

Note

  • If try with multiple except blocks available then default except block should be last, otherwise we will get SyntaxError.

Example

Python
try:
  print(10/0)
except:
  print("Default Except")
except ZeroDivisionError:
  print("ZeroDivisionError")

Output

PowerShell
SyntaxError: default 'except:' must be last

Finally block

  • It is not recommended to maintain clean up code (Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarantee for the execution of every statement inside try block always.
  • 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 we required some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled. Such type of best place is nothing but finally block. Hence the main purpose of finally block is to maintain clean up code.

Syntax

Python
try:
  # Risky Code
except:
  # Handling Code
finally:
  # Cleanup code

Case-1: If there is no exception

Python
try:
  print("try")
except:
  print("except")
finally:
  print("finally")

Output

PowerShell
try
finally

Case-2: If there is an exception raised but handled

Python
try:
  print("try")
  print(10/0)
except ZeroDivisionError:
  print("except")
finally:
  print("finally")

Output

PowerShell
try
except
finally

Case-3: If there is an exception raised but not handled

Python
try:
  print("try")
  print(10/0)
except NameError:
  print("except")
finally:
  print("finally")

Output

PowerShell
try
finally
ZeroDivisionError: division by zero

Note

  • There is only one situation where finally block won’t be executed i.e. whenever we are using os._exit(0) function.
  • Whenever we are using os._exit(0) function then python virtual machine itself will be shutdown. In this particular case finally won’t be executed.

Example

Python
import os
try:
  print("try")
  os._exit(0)
except NameError:
  print("except")
finally:
  print("finally")

Output

PowerShell
try

Control Flow in try-except-finally

Syntax

Python
try:
  stmt-1
  stmt-2
  stmt-3
except:
  stmt-4
finally:
  stmt-5
stmt6

Case-1: If there is no exception

PowerShell
stmt-1
stmt-2
stmt-3
stmt-5
stmt-6
  • Normal termination

Case-2: If an exception raised at stmt2 and the corresponding except block matched

PowerShell
stmt-1  
stmt-4
stmt-5
stmt-6
  • Normal termination

Case-3: if an exception raised at stmt2 but the corresponding except block not matched

PowerShell
stmt-1
stmt-5
  • Abnormal termination

Case-4:If an exception raised at stmt4

PowerShell
stmt-1
stmt-2
stmt-3
stmt-5
stmt-6
  • Normal termination

Case-5:If an exception raised at stmt-5 or at stmt-6 then it is always abnormal termination.

PowerShell
stmt-1
stmt-2
stmt-3
  • Abnormal termination

Using else block with try-except-finally

Syntax

Python
try:
  # Risky Code
except:
  # Will be executed if exception inside try
else:
  # Will be executed if there is no exception inside try
finally:
  # Will be executed whether exception raised or not raised and handled or not
  # handled
  • We can use else block with try-except-finally blocks.
  • else block will be executed if and only if there are no exceptions inside try block.

Example

Python
try:
  print("try")
  # print(10/0)
except:
  print("except")
else:
  print("else")
finally:
  print("finally")

Output

PowerShell
try
else
finally
  • If we are uncommenting line 3 then else block won’t be executed because there is exception inside try block. In this case output is:
PowerShell
try
except
finally

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error