It sometimes happens that we might be faced with some unexpected situations while executing our programming codes. In such situations, it might so happen that we don’t how to get out of those situations. Thus, there comes the case of Exceptions and Exceptions handling. Also, in Python programming there is a very clearly established way to deal with these exceptions. In this post, we’ll, thus, cover how does Python catch all exception and handle the errors, in the best way.

So, What is an Exception?

Exceptions are the mistakes that happen during an execution of a program. When the errors occur, Python generally generates an exception which will be handled by it, and thus it avoids your program from crashing.

Need for Exceptions? — How does Python Catch all Exception

Exceptions are convenient in various ways for handling errors and special conditions in a program. When you think that you’ve got a code which may produce a mistake then you shall use the power of exception handling.

Now, How do we Raise an Exception?

You can raise an exception in your own program by using the raise exception
statement. Raising an exception breaks current code execution and returns the exception back until it’s taken care of.

 Python catch all Exception

Types of Exceptions :-

Sr.No.Exception Name —> Description
1Exception —> Base class for all exceptions
2SystemExit —> Raised by the sys.exit() function.
3ZeroDivisionError —> Raised when division or modulo by zero takes place for all numeric types.
4AssertionError —> Raised in case of failure of the Assert statement.
5EOFError —> Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
6IndexError —> Raised when an index is not found in a sequence.
7KeyError —> Raised when the specified key is not found in the dictionary.
8NameError —> Raised when an identifier is not found in the local or global namespace.
9IOError —> Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
10SyntaxError —> Raised when there is an error in Python syntax.
11IndentationError —> Raised when indentation is not specified properly.
12TypeError —> Raised when an operation or function is attempted that is invalid for the specified data type.
13ValueError —> Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
14RuntimeError —> Raised when a generated error does not fall into any category.

Examples of Various Exception Errors

Now, that we know what a number of the exception errors mean, thus, let’s get back to work and see some examples for ourselves to better understand the topic.

except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found within the file.')
except ImportError:
print ("No module found" )
except SyntaxError:
print('There is an error in your syntax.')
except EOFError:
print('You reached the End of File')
except ZeroDivisionError:
print ("Is it possible to divide by Zero? Huh! ..")
print('An error occurred.')

Python Catch all Exception — Exceptions Handling

Now, that we know : What are Exceptions? Also, the examples of Exceptions? Categories of Exceptions? Then, we must get to know how to use the process of Exception handling in Python.

The words “try” and “except” are Python keywords and are the ones used to catch exceptions.

try-except [exception-name] blocks
  • The code within the try clause are going to be executed statement by statement.
  • If an exception occurs, the remainder of the try block are going to be skipped and therefore the except clause are going to be executed.
### The try-except syntax ::::

some statements here
exception handling


print 1/0

except ZeroDivisionError:
print ("Is it possible to divide by Zero? Huh! ..")

Lets see some other Code Examples :

num = int(raw_input("Enter any number between 1 to 50"))
print "The number you entered is : ", num

What does the above program do? It asks you to input any number between 1 to 50. This program works perfectly fine till the user enters numbers. But what will happen if the user puts in something else (like a string)?

Enter any number between 1 to 50

You can see that the program throws us a mistake once we enter a string.

Traceback (most recent call last):
File "", line 1, in
num = int(raw_input("Enter any number between 1 to 50"))
ValueError: invalid literal for int() with base 10: 'Shubham'

#### ValueError is an exception error type. Now, let’s focus on how to handle this error and fix the program and get it running again.
import sys

num = int(raw_input("Enter any number between 1 to 50"))

except ValueError: 
print "There is an error encountered. Please enter numbers only !!"

print "The number you entered is : ", num

### If we now run the program, and enter a string (instead of a number), we will see that we get a special output.
Enter any number between 1 to 50
There is an error encountered. Please enter numbers only !!

The try-except-else clause

The else clause during a try-except clause/statement must follow all except clauses. This is thus, useful for code that has got to be executed if the try clause doesn’t raise an exception.

data = something_that_can_go_wrong

except IOError: 

  • Also, exceptions within the else clause aren’t handled by the preceding except clauses.
  • Make sure that the else clause is run before the finally block.

The try-finally clause

  • The finally clause is generally optional.
  • Also, it is generally only intended to define the clean-up actions that should be executed under every circumstance.
raise KeyboardInterrupt

print ‘Bye Bye, Shubham ....’
Bye Bye, Shubham ...
  • A finally clause usually executes before leaving the try statement, whether an exception has occurred or not.
  • Also, remember that if you don’t specify an exception type on the except line, it will catch all exceptions.
  • This may be a bad idea, since it means your program will ignore the various unexpected errors also.
  • Also, it being like the ones which the except block is really prepared to handle.
 Python catch all Exception

–> SUMMING UP — Python Catch all Exception

Through this article, thus, I have tried to provide you with knowledge about what exactly is an Exception and how does Python catch all Exception and handles them. Also, other trendy topics of problems and questions related to it. So, in writing this, I suppose I have made myself pretty clear. But, in case, you persist with any doubts, then, please feel free to write to me in the comments section and I am as always ever-ready to help you out with your queries and problems.

Until then bidding you Good-Bye !!! Ok, wait ….. before you go, you may check out my various other posts. Also, for the simple reason, that is, to enhance your knowledge on various other topics of importance. Where ??? Here……

Categorized in: