All Courses

Download our e-book of Introduction To Python

Top Courses

Master's In Artificial Intelligence Job Guarantee Program

4.5 (1,292 Ratings)

559 Learners

Webinars

How To Land a Job in Data Science?

Feb 9th (7:00 PM) 182 Registered
More webinars

Python Design Patterns - Exception Handling

Neha Kumawat

a year ago

Python Design Pattern
Table of Content
  • Why use exceptions?
  • Example – Division by zero
  • Output
  • Raising Exceptions
  • Syntax
              Handling exceptions is also a primary criterion of design patterns. An exception is an error that happens during the execution of a program. When a particular error occurs, it is important to generate an exception. This helps in curbing program crashes.

Why use exceptions?

          Exceptions are convenient ways of handling errors and special conditions in a program. When a user thinks that the specified code can produce an error then it is important to use exception handling.

Example – Division by zero


import sys

randomList = ['a', 0, 2]

for entry in randomList:
   try:
      print("The entry is", entry)
      r = 1/int(entry)
      break
   except:
      print("Oops!",sys.exc_info()[0],"occured.")
      print("Next entry.")
      print()
print("The reciprocal of",entry,"is",r)

Output

The above program generates the following output −

Raising Exceptions

          In Python programming specifically, exceptions are raised when corresponding error of code occurs at run time. This can be forcefully raised using the “raise” keyword.

Syntax


   raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt
   Like the Blog, then Share it with your friends and colleagues to make this AI community stronger. 
To learn more about nuances of Artificial Intelligence, Python Programming, Deep Learning, Data Science and Machine Learning, visit our insideAIML blog page.
Keep Learning. Keep Growing. 

Submit Review