Python ExceptionsWhen a Python program meets an error, it stops the execution of the rest of the program. An error in Python might be either an error in the syntax of an expression or a Python exception. We will see what an exception is. Also, we will see the difference between a syntax error and an exception in this tutorial. Following that, we will learn about trying and except blocks and how to raise exceptions and make assertions. After that, we will see the Python exceptions list. What is an Exception?An exception in Python is an incident that happens while executing a program that causes the regular course of the program's commands to be disrupted. When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that describes an error is called an exception. When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit. Exceptions versus Syntax ErrorsWhen the interpreter identifies a statement that has an error, syntax errors occur. Consider the following scenario: Code Output: if (s != o: ^ SyntaxError: invalid syntax The arrow in the output shows where the interpreter encountered a syntactic error. There was one unclosed bracket in this case. Close it and rerun the program: Code Output: 2 string = "Python Exceptions" 4 for s in string: ----> 5 if (s != o): 6 print( s ) NameError: name 'o' is not defined We encountered an exception error after executing this code. When syntactically valid Python code produces an error, this is the kind of error that arises. The output's last line specified the name of the exception error code encountered. Instead of displaying just "exception error", Python displays information about the sort of exception error that occurred. It was a NameError in this situation. Python includes several built-in exceptions. However, Python offers the facility to construct custom exceptions. Try and Except Statement - Catching ExceptionsIn 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. Let's see if we can access the index from the array, which is more than the array's length, and handle the resulting exception. Code Output: The index and element from the array is 0 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 The code blocks that potentially produce an error are inserted inside the try clause in the preceding example. The value of i greater than 2 attempts 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. How to Raise an ExceptionIf a condition does not meet our criteria but is correct according to the Python interpreter, we can intentionally raise an exception using the raise keyword. We can use a customized exception in conjunction with the statement. If we wish to use raise to generate an exception when a given condition happens, we may do so as follows: Code 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. Assertions in PythonWhen we're finished verifying the program, an assertion is a consistency test that we can switch on or off. The simplest way to understand an assertion is to compare it with an if-then condition. An exception is thrown if the outcome is false when an expression is evaluated. 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. The assert StatementPython examines the adjacent expression, preferably true when it finds an assert statement. Python throws an AssertionError exception if the result of the expression is false. The syntax for the assert clause is − Python uses ArgumentException, if the assertion fails, as the argument for the AssertionError. We can use the try-except clause to catch and handle AssertionError exceptions, but if they aren't, the program will stop, and the Python interpreter will generate a traceback. Code Output: 7 #Calling function and passing the values ----> 8 print( square_root( 36 ) ) 9 print( square_root( -36 ) ) Input In [23], in square_root(Number) 3 def square_root( Number ): ----> 4 assert ( Number < 0), "Give a positive integer" 5 return Number**(1/2) AssertionError: Give a positive integer Try with Else ClausePython 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. Here is an instance of a try clause with an else clause. Code Output: 0.25 We cannot divide by zero Finally Keyword in PythonThe finally keyword is available in Python, and it 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. Here is an example of finally keyword with try-except clauses: Code Output: Atepting to divide by zero This is code of finally clause User-Defined ExceptionsBy inheriting classes from the typical built-in exceptions, Python also lets us design our customized exceptions. Here is an illustration of a RuntimeError. In this case, a class that derives from RuntimeError is produced. Once an exception is detected, we can use this to display additional detailed information. We raise a user-defined exception in the try block and then handle the exception in the except block. An example of the class EmptyError is created using the variable var. Code Output: 2 try: ----> 3 raise EmptyError( "The variable is empty" ) 4 except (EmptyError, var): EmptyError: The variable is empty Python Exceptions ListHere is the complete list of Python in-built exceptions.
SummaryWe learned about different methods to raise, catch, and handle Python exceptions after learning the distinction between syntax errors and exceptions. We learned about these clauses in this tutorial:
Here is the syntax of try, except, else, and finally clauses. Syntax: Next TopicPython Date and Time |