Python – Exceptions:
In this tutorial, we will learn about the handling exceptions in Python. It is quite common that for any program written in any programming language may hit the error during the execution due to any reasons.
Reasons may be the syntactical error, or conditional or operational errors caused due to filesystem or due to the lack required resources to execute the program.
So, we need to handle those kind of exceptions or errors by using different clauses while we do programming.
In Python, we can handle an exception by using the raise exception statement or using the try, except clauses.
Syntax:
try: raise statement except x statement
Exceptions are 2 types:
- Pre-defined exceptions:
These are the Exceptions which are existing within the python programming language as Built-in Exceptions. Some of them are arithmetic errors like ZeroDivisionError, FloatingPointError, EOF errors… etc.
- User-defined exceptions:
These exceptions are created by programmer which are derived from Exception class
Example of Handling an Exception:
>>> while True: ... try: ... x = int(input("Please enter a number: ")) ... print("The number entered is :", x) ... break ... except ValueError: ... print("Sorry !! the given number is not valid number. Try again...") ...
Output:
Please enter a number: abc
Sorry !! the given number is not valid number. Try again…
Please enter a number: apple
Sorry !! the given number is not valid number. Try again…
Please enter a number: a123
Sorry !! the given number is not valid number. Try again…
Please enter a number: 123
The number entered is : 123
Example by using the Predefined Exception:
>>> try: ... print(100/0) ... except ZeroDivisionError as error: ... print(" we Handled predefined error:", error) ...
Output:
we Handled predefined error: division by zero