Exception Handling in Python

Exception handling in Python

When a Python script raises an exception, it must handle the exception immediately otherwise it terminates and quits or program crashes. If you have some code, there may occurs error (suspicious code) , then put it into try block.  Putting the code into try  block is very effective way to handle exception.

What is Exception?

Exceptions are the errors occurs at execution time. We can say exception is an signal which tells us an error or any other abnormal condition occurs in our code.

exception handling
exception handling

Let’s understand it by taking an example, suppose you are listening a song on you tube, during the song there may be network error that causes your song to stop. This kind of situation which causes to halt normal process or flow is called exception. And your action, what you do in that situation is called exception handling.

Types of Exceptions in Python

There is various types of built-in exceptions in python. These occurs during execution of the program. here is the list of exceptions:

  1. IOError : It raised when an input/output operation fails such as opening a file, print statement etc.
  2. ZeroDivisionError : It is an type of arithmetic error, which occurs if an number is divided to zero . Ex. print(1/0).
  3. Import Error : It occurs when an import statement fails to find given module . Ex. import abc, if there is no module named abc.
  4. NameError : It occurs when a local or global name is not found. This applies only to undefined names.
  5. Arithmetic Error : It is the base class for all errors, that occurs due to arithmetic operations. Such as ZeroDivisionError, OverflowError, FloatingPointError.
  6. EOFError :  It is also called End Of File error. It occurs when file end is not done in right way. For example if we skip to add parenthesis in print statement i.e print(“Hello”
  7. IndexError : It occurs when a sequence’S  is out of range. For Ex. list = [1,2,3] , if we print(li[5]), then this error will occur, because li has no index 5.
  8. KeyError : It occurs when a dictionary’s key is not found in the given set of keys.
  9. KeyboardInterrupt :  It occurs when a user press interrupt key (delete or ctrl+c ) during the execution of the program.
  10. MemoryError :  This kind of exception occurs when an operation goes out of memory. It can be handled by deleting some objects.
  11. SyntaxError:  It occurs when a parser encounters wrong syntax.
  12. IndentationError : As python maintains indentation. Block of code in python defines with proper indentation(space). If the block of code does not matches indentation (space) level, then this error will occur.

What is exception handling?

As we discuss earlier exception is an event, that occurs at run-time and disturbs the normal flow of program. The process of responding to such situations (exceptions) is called exception handling. The object which causes exception is called Exception object. Exception object contains information about type of exception.

Exception handling in Python

When a Python script raises an exception, it must handle the exception immediately otherwise it terminates and quits or program crashes. If you have some code, there may occurs error (suspicious code) , then put it into try block.  Putting the code into try  block is very effective way to handle exception.

Try – except- else clause

  • The malicious code is placed inside try block.
  • Try block is followed by the except block.
  • Try and Except both have their own block of code.
  • If there is no exception, the code written in try block will execute.
  • If error occurs, the code in except block will execute.
  • Except may followed by name of different exception types.
  • Is there is no exception, else block will execute.

Syntax

try:
      -------
      malicious code goes here
      -------

except Exception1:

      code to execute if exception one

except Exception2:

      code to execute if Exception 2

except ExceptionN:

      code to execute for ExceptionNth
else:
      if no exception occured, executes the else block code

Example

Exception Handling
Exception Handling

Output

output: Exception Handling
output: Exception Handling

In the example above, i have handle two  exceptions NameError and IOError, i have comment out IOError code (line 2,3) .Try to remove comment and u will see the except IOError block will execute.

If we do not handle exceptions (Not use try-except), then following error will occur in above code:

Traceback (most recent call last):
File "exceptions.py", line 6, in <module>
print(nm) ##Name error will occur
NameError: name 'nm' is not defined
Note

If there occurs an error, that affects the try block itself (e.g syntax error). There still will be an error because it affects try , except or finally itself. These may not use for syntax error, these are only used for user inputs.

Except with no Exceptions

If we don’t remember the name of error, then simply write except . In that case there is no need to specify specific error.  It can also use in situation, when we not expect any specific type of error/ exception.

Syntax

try:  
        malicious code goes here
except:  
        code to be execute in case of exception occurs
else:  
        code to be execute if there is no Exception

Example:

Exception Handling
Exception Handling

Output:

Output: Exception Handling
Output: Exception Handling

Except with Multiple exceptions

We can declare Except block with multiple statements. If we want to perform common action for multiple exceptions, then you can put all exceptions with single except block , separate by comma.

Syntax

try:  

    malicious code goes here 

except(Exception1,Exception2,Exception3,..,ExceptionN)  

    execute this code in case of any Exception of above occur 
else:  
    execute code in case no exception occurred

Example

Exception Handling
Exception Handling

Output

Output: Exception handling
Output: Exception handling

The Finally Block

The code written in finally block, runs continuously even if there is an exception in try block. We can say exceptions does not effects try block. If there is a code which we want to execute anyway, no matter Exception occur or not, then put this code into finally block.

Syntax

try:
     malicious code
finally:
    code must to be execute

Example

Exception Handling
Exception Handling

Output

Output: Exception Handling
Output: Exception Handling

Raise an Exception

You can throw an exception in python using raise keyword. Raise will cause an exception to occur. So we can take advantage of exception handling by raising an exception. The syntax of Raising an exception is as follows:

Syntax

raise Exception(<argument>)

Here Exception is the name of exception, where arguments are values of exception, which we will clear in example (line 4). Value of an exception is optional.

Example

Exception Handling
Exception Handling

Output

Output: Exception handling
Output: Exception handling
  • Raising exception makes program more controllable.
  • We can raise an exception with its value.
  • The value must given in parenthesis just after the name of exception .
  • We can access value with the help of ‘as‘.
  • In above example (line 6), ‘value‘ is an reference variable which holds the value of exception.

User defined exception or Custom exception

  • Python also allows us to create our own exception classes.
  • It will derive from the standard built-in Exception class.
  • Creating our own exception class is known as Custom exception or user defined exception.
  • We can also create custom class with its value (argument)
  • Raising and accessing Error is just like creating an instance of class.

If you don’t know more about oops then you can visit Python OOPs

 

Example

Custom Exception
Custom Exception

Output

Output: Exception Handling
Output: Exception Handling

So it is all about exceptions and exception handling. Thanks

 

52 thoughts on “Exception Handling in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Youre so cool! I dont suppose Ive learn something like this before. So good to seek out any person with some original ideas on this subject. realy thanks for beginning this up. this web site is something that is wanted on the internet, someone with slightly originality. helpful job for bringing something new to the internet!

  2. Just desire to say your article is as astounding. The clarity in your post is just excellent and that i can assume you’re a professional in this subject. Fine along with your permission allow me to seize your RSS feed to stay updated with drawing close post. Thank you one million and please continue the enjoyable work.

  3. Normally I do not read post on blogs, but I would like to say that this write-up very compelled me to try and do it! Your writing taste has been amazed me. Thanks, very nice post.

  4. I am now not certain where you’re getting your information, but great topic. I needs to spend a while finding out much more or working out more. Thanks for fantastic information I used to be searching for this info for my mission.

  5. It’s perfect time to make some plans for the future and it is time to be happy. I have read this post and if I could I want to suggest you few interesting things or suggestions. Maybe you could write next articles referring to this article. I wish to read even more things about it!

  6. Wow! This could be one particular of the most beneficial blogs We’ve ever arrive across on this subject. Actually Great. I am also a specialist in this topic so I can understand your effort.

  7. I just want to tell you that I am beginner to blogging and site-building and really loved this web blog. Probably I’m planning to bookmark your site . You surely come with perfect writings. Many thanks for sharing with us your website page.

  8. I do enjoy the way you have framed this problem and it does give us some fodder for thought. However, coming from what precisely I have seen, I only trust as the reviews stack on that people today continue to be on point and in no way embark on a tirade associated with the news of the day. Yet, thank you for this superb piece and though I can not necessarily concur with it in totality, I regard the viewpoint.

  9. of course like your website but you need to check the spelling on quite a few of your posts. Several of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I’ll certainly come back again.

  10. This is the correct weblog for anybody who wants to find out about this topic. You realize a lot its nearly hard to argue with you (not that I really would want…HaHa). You definitely put a brand new spin on a topic thats been written about for years. Great stuff, just great!

  11. Outstanding post however I was wanting to know if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further. Kudos!

  12. That is the proper blog for anyone who desires to search out out about this topic. You notice so much its virtually arduous to argue with you (not that I truly would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, simply nice!

  13. Hello! I understand this is sort of off-topic however I needed to ask.
    Does building a well-established website like yours require a massive amount work?
    I’m brand new to operating a blog however I do write in my
    diary every day. I’d like to start a blog so I
    will be able to share my own experience and feelings online.

    Please let me know if you have any kind of recommendations or tips for new aspiring bloggers.

    Appreciate it!

  14. The root of your writing while sounding agreeable at first, did not really sit very well with me after some time. Someplace within the paragraphs you managed to make me a believer unfortunately only for a while. I however have got a problem with your leaps in logic and you might do well to help fill in all those breaks. In the event that you can accomplish that, I will surely be impressed.

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.