An exception in Python is an occurrence that causes a disruption in the commands of the program while being executed. When a Python code meets a condition that it cannot handle the execution, it raises an exception. An object in Python that describes an error is called an exception.
Exception handling is a method in Python that is used to manage and respond to errors and debugging that occur while the execution of the code is taking place.
When the Python program encounters an error and raises an exception, it can lead to a program crash, but before that happens, Python provides a Traceback message that lets us know about the problem.
A syntax error is a type of error when the compiler finds that there is something incorrect in the statement. Apart from this, an error message is also generated to help us find out what went wrong.
Output:
Cell In[1], line 1
if x > 5
^
SyntaxError: expected ':'
Explanation
In the above example, a syntax error is raised because the if conditional statement is missing the ':'. When we add the missing part, the code runs perfectly fine.
An exception error is a runtime error that occurs while the program is running, even though the code syntax is correct.
Output:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[2], line 4
1 x = 10
2 y = 0
----> 4 result = x / y
5 print(result)
ZeroDivisionError: division by zero
Explanation
In the above example, there is syntactically nothing wrong, but an exception error is raised because a number cannot be divided by zero. The last line of the output determines the type of exception error that has occurred.
In Python, we catch exceptions and handle them using try and except code blocks. The try clause contains the code that can raise an exception, while the except clause contains the code lines that handle the exception.
The try and except statements help in preventing the crashing of the program when an error occurs by producing an alternative code.
Output:
The index and element from the array is 0 in Python The index and element from the array is 1. Exceptions The index and element from the array is 2 try and except Index out of range
Explanation
The code blocks that potentially produce an error are inserted inside the try clause in the preceding example. The value of i is greater than 2, attempting to access the list's item beyond its length, which is not present, resulting in an exception. The except clause then catches this exception and executes code without stopping it.
In Python, the raise statement comes into play when we need to manually trigger an error when something goes wrong. It helps in identifying the specific issue in the code by raising a custom or built-in exception, even if no error has occurred yet.
If we wish to use raise to generate an exception when a given condition happens, we may do so as follows:
Output:
1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Exception: Length of the given list must be less than or equal to 3 but is 4
The implementation stops and shows our exception in the output, providing indications as to what went incorrect.
In Python, Assertions are statements that are used to verify assumptions in a program. They act as internal checks during development and debugging. If an assertion condition turns out to be false, Python raises an AssertionError and stops execution.
Assertions are made via the assert statement, which was added in Python 1.5 as the latest keyword.
Assertions are commonly used at the beginning of a function to inspect for valid input and at the end of calling the function to inspect for valid output.
We can use the try-except clause to catch and handle AssertionError exceptions, but if they are not, the program will stop, and the Python interpreter will generate a traceback.
Output:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[4], line 9
7 #Calling function and passing the values
8 print( square_root( 36 ) )
----> 9 print( square_root( -36 ) )
Cell In[4], line 4
3 def square_root( Number ):
----> 4 assert Number >= 0, "Give a positive integer"
5 return Number**(1/2)
AssertionError: Give a positive integer
Python also supports the else clause, which should come after every except clause, in the try, and except blocks. Only when the try clause fails to throw an exception the Python interpreter goes on to the else block.
Output:
0.25 We cannot divide by zero
The finally keyword is always used after the try-except block. The finally code block is always executed after the try block has terminated normally or after the try block has terminated for some other reason.
Output:
Attempting to divide by zero This is code of finally clause
User-defined exceptions are the type of exceptions that enables developers to create custom error types according to specific application logic. They make error handling clearer, more expressive, and easier to debug if we compare it by just depending on the built-in exceptions.
We raise a user-defined exception in the try block and then handle the exception in the except block.
Output:
Invalid roll number: 150. Roll number must be between 1 and 100
| S.N. | Name of the Exception | Description of the Exception |
|---|---|---|
| 1 | Exception | All exceptions of Python have a base class. |
| 2 | StopIteration | If the next() method returns null for an iterator, this exception is raised. |
| 3 | SystemExit | The sys.exit() procedure raises this value. |
| 4 | StandardError | Excluding the StopIteration and SystemExit, this is the base class for all Python built-in exceptions. |
| 5 | ArithmeticError | All mathematical computation errors belong to this base class. |
| 6 | OverflowError | This exception is raised when a computation surpasses the numeric data type's maximum limit. |
| 7 | FloatingPointError | If a floating-point operation fails, this exception is raised. |
| 8 | ZeroDivisionError | For all numeric data types, its value is raised whenever a number is attempted to be divided by zero. |
| 9 | AssertionError | If the Assert statement fails, this exception is raised. |
| 10 | AttributeError | This exception is raised if a variable reference or assigning a value fails. |
| 11 | EOFError | When the endpoint of the file is approached, and the interpreter didn't get any input value by raw_input() or input() functions, this exception is raised. |
| 12 | ImportError | This exception is raised if using the import keyword to import a module fails. |
| 13 | KeyboardInterrupt | If the user interrupts the execution of a program, generally by hitting Ctrl+C, this exception is raised. |
| 14 | LookupError | LookupErrorBase is the base class for all search errors. |
| 15 | IndexError | This exception is raised when the index attempted to be accessed is not found. |
| 16 | KeyError | When the given key is not found in the dictionary to be found in, this exception is raised. |
| 17 | NameError | This exception is raised when a variable isn't located in either local or global namespace. |
| 18 | UnboundLocalError | This exception is raised when we try to access a local variable inside a function, and the variable has not been assigned any value. |
| 19 | EnvironmentError | All exceptions that arise beyond the Python environment have this base class. |
| 20 | IOError | If an input or output action fails, like when using the print command or the open() function to access a file that does not exist, this exception is raised. |
| 22 | SyntaxError | This exception is raised whenever a syntax error occurs in our program. |
| 23 | IndentationError | This exception was raised when we made an improper indentation. |
| 24 | SystemExit | This exception is raised when the sys.exit() method is used to terminate the Python interpreter. The parser exits if the situation is not addressed within the code. |
| 25 | TypeError | This exception is raised whenever a data type-incompatible action or function is tried to be executed. |
| 26 | ValueError | This exception is raised if the parameters for a built-in method for a particular data type are of the correct type but have been given the wrong values. |
| 27 | RuntimeError | This exception is raised when an error that occurred during the program's execution cannot be classified. |
| 28 | NotImplementedError | If an abstract function that the user must define in an inherited class is not defined, this exception is raised. |
An exception in Python is an occurrence that causes a disruption in the commands of the program while being executed. An error occurs when the compiler finds that there is something incorrect in the statement is a Syntax error.
An exception is a runtime error that occurs while the program is running, even though the code syntax is correct. We covered various topics such as how to raise exceptions, assertions in Python, the finally keyword, the try with else clause, user-defined exceptions, etc.
We request you to subscribe our newsletter for upcoming updates.