The exception is caught by the except block. In the above example, we are dividing a number by 0 inside the try block. And, for each try block, there can be only one finally block. In Python, the finally block is always executed no matter whether there is an exception or not. Note: Exceptions in the else clause are not handled by the preceding except clauses. However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding except. If we pass an even number, the reciprocal is computed and displayed. If we pass an odd number: Enter a number: 1 Let's look at an example: # program to print the reciprocal of even numbers In some situations, we might want to run a certain block of code if the code block inside try runs without any errors.įor these cases, you can use the optional else keyword with the try statement. The set of code inside the Inde圎rror exception is executed.The ZeroDivisionError exception is skipped.When the Inde圎rror exception occurs in the try block, Here, we are trying to access a value to the index 5. Notice the statement, print(even_numbers) Since the list index starts from 0, the last element of the list is at index 3. In this example, we have created a list named even_numbers. The argument type of each except block indicates the type of exception that can be handled by it. The quotient of dividing an even number by an odd number, which results in an even number or a mixed number, for example: 12/3 4, or 12/7 1.71 i.e.: An even number ÷ an odd number an even number or a mixed number. Multiple except blocks allow us to handle each exception differently. If none of the statements in the try block generates an exception, the except block is skipped.įor each try block, there can be zero or more except blocks. The except block catches the exception and statements inside the except block are executed. Now when an exception occurs, the rest of the code inside the try block is skipped. To handle the exception, we have put the code, result = numerator/denominator inside the try block. In the example, we are trying to divide a number by 0. # Output: Error: Denominator cannot be 0. Example: Exception Handling Using try.except try: The except block cannot be used without the try block. When an exception occurs, it is caught by the except block. Every try block is followed by an except block. Here, we have placed the code that might generate an exception inside the try block. Here's the syntax of try.except block: try: The try.except block is used to handle exceptions in Python. This is why it is important to handle exceptions. We know that exceptions abnormally terminate the execution of a program. In the last tutorial, we learned about Python exceptions.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |