Python Exceptions PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document is a Python tutorial that explains exception handling in Python using try-except blocks and how to deal with different kinds of exceptions like ZeroDivisionError, ValueError, and TypeError. The document presents practical examples and scenarios to illustrate the use of these exception handling mechanisms in real-world programming situations.
Full Transcript
a= 5 b = 0 c = a/b print(c) Exception handling is a mechanism to handle errors and other exceptional events that occur during program execution. When Python encounters an error, it raises an exception. Exceptions stop the normal flow of a program, and without handling...
a= 5 b = 0 c = a/b print(c) Exception handling is a mechanism to handle errors and other exceptional events that occur during program execution. When Python encounters an error, it raises an exception. Exceptions stop the normal flow of a program, and without handling them, the program would crash. Using exception handling, you can define what the program should do when it encounters a particular error, allowing it to continue running smoothly or to exit gracefully. Scenario: Ordering Food at a Restaurant try: You decide to order a particular dish from the menu and give your order to the waiter. This is your “try” – the part where you assume things will go smoothly, and the dish will arrive as expected. except: Item Out of Stock: If the dish you ordered isn’t available, the waiter (like the program) will tell you, “Sorry, we’re out of that dish.” You handle this exception by ordering something else. Allergies: Suppose you’re allergic to peanuts, and after ordering, the waiter realizes the dish contains peanuts. They might warn you to prevent a reaction. In this case, you would handle this by choosing a different dish or asking for modifications. else: If there are no issues, the dish you ordered arrives just as you wanted, and you enjoy your meal. This is like the else block, where everything proceeds as expected without any issues. finally: No matter what, you pay the bill at the end. Whether you got the dish you wanted, had to change your order, or even if there was a delay in service, you still settle the bill before leaving. The finally block in code works similarly by running at the end regardless of the outcome, often to clean up resources. Try-Except Structure: The try block lets you test a block of code 1. try: 2. file = open("data.txt", "r") for errors. 3. except FileNotFoundError: 4. print("File not found") The except block lets you handle the error. 5. else: 6. # Runs if no exception occurs The else block lets you execute code 7. content = file.read() 8. print(content) when there is no error. 9. finally: 10. # Always runs, regardless of exceptions The finally block lets you execute code, 11. file.close() regardless of the result of the try- and except blocks. #Program to perfrom division and understand exception handling a = int (input('Enter the first number:’)) #input: 1 b = int (input('Enter the second number: ‘)) #input: 2 try: res = a / b print('result = ', res) except: print('Exception Handled ') print('End of program’) #result: Exception Handled # End of program #Program to know the type of exception import sys a = int (input('Enter the first number ')) b = int ( input('Enter the second number ')) try: res = a / b print('result = ', res) except: print('Exception Handled ') print("Oops!", sys.exc_info() ,"occured.") print('End of program') import sys try : num = int (input('Enter the numerator ') ) den = int (input('Enter the denominator ' ) ) result = num / den; print('Result = ',result) except ValueError: print('Invalid Input') except ZeroDivisionError: print('Divide by Zero Error') print('End of Program ') #Program to demonstrate multiple except (catch) blocks try: a = input('Enter the first number ') b = input('Enter the second number ') a = int(a) res = a + b print('result = ', res) except ValueError: print('Invalid Input Error') except TypeError: print('Type Error') except ZeroDivisionError: print('Divide by Zero Error') print('End of program') Multiple exceptions can also be put into a single **except** block using parentheses, to have the **except** block handle all of them. #Program to demonstrate handling multiple exception types in a single block import sys try: a = input('Enter the first number ') b = input('Enter the second number ') a = int(a) b = int(b) sum = a + b print('sum = ', sum) quotient = a // b print('quotient = ', quotient) except (ValueError, TypeError): print('Invalid Input Error: ', sys.exc_info()) except ZeroDivisionError: print('Divide by Zero Error') print('End of program') try: print('Enter the marks') marks = int(input()) if marks < 0 or marks > 100: raise ValueError #write code to calculate grade except ValueError: print('Input out of range') def divide (num, den): try: res = num / den return res except ZeroDivisionError: print('Divide Function: Divide by Zero Error') raise try : num = int (input('Enter the numerator ') ) den = int (input('Enter the denominator ') ) result = divide (num, den) print('Result = ', result) except ValueError: print('Main Block : Invalid Input ') except ZeroDivisionError: print('Main Block: Divide by Zero error') print('End of Program ') To ensure some code runs no matter what errors occur, you can use a finally statement. The finally statement is placed at the bottom of a try/except statement. Code within a finally statement always runs after execution of the code in the try, and possibly in the except, blocks. #Program to demonstrate finally blocks try: a = int(input('Enter the first number ')) b = int(input('Enter the second number ')) res = a / b print('result = ', res) except (ValueError, TypeError): print('Invalid Input Error') except ZeroDivisionError: print('Divide by Zero Error') finally: print('This code will run no matter what') print('End of program') Raising exception is similar to throwing exception in C++/Java. You can raise exceptions by using the raise statement class InvalidRange(Exception): pass try: marks = input('Enter the marks : ') marks = int(marks) if (marks < 0 or marks > 100): raise InvalidRange print('Marks = ', marks) except ValueError: print('Invalid Input') except InvalidRange: print('Input value out of range') Types of Exceptions 1. SyntaxError 2. TypeError 3. NameError 4. IndexError 5. KeyError 6. ValueError 7. AttributeError 8. IOError 9. ZeroDivisionError 10.ImportError SyntaxError This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis. SyntaxError try: SyntaxError is the type of exception we're exec("print('Hello") trying to catch. except SyntaxError as e: as e assigns the exception object to e. print("A syntax error occurred:", e) You can then print e or access its attributes print("Error message:", e.msg) to see the specific error details. TypeError This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer. TypeError Trying to concatenate a string ("The answer is: ") with an integer (42) raises a try: TypeError, because Python does not automatically convert integers to strings in result = "The answer is: " + 42 concatenations. except TypeError as e: print("A TypeError occurred:", e) The except TypeError as e: block catches the error and prints it. NameError This exception is raised when a variable or function name is not found in the current scope. NameError unknown_variable has not been defined, so trying to print(unknown_variable) raises a try: NameError. The except NameError as e: block catches print(unknown_variable) the error and prints a message along with except NameError as e: print("A NameError occurred:", e) the error details. IndexError This exception is raised when an index is out of range for a list, tuple, or other sequence types. IndexError The list numbers has only three elements (with indices 0, 1, and 2). try: Attempting to access numbers raises an IndexError because index 5 is out of range. numbers = [1, 2, 3] The except IndexError as e: block catches print(numbers) except IndexError as e: the error and prints an informative print("An IndexError occurred:", e) message. KeyError This exception is raised when a key is not found in a dictionary. KeyError The dictionary person has keys "name" and "age", but no key "address". try: Attempting to access person["address"] raises a KeyError. person = {"name": "Alice", "age": 30} The except KeyError as e: block catches print(person["address"]) except KeyError as e: the error and prints a message with details print("A KeyError occurred:", e) about the missing key. ValueError This exception is raised when a function or method is called with an invalid argument or input, such as trying to convert a string to an integer when the string does not represent a valid integer. ValueError The int() function expects a string that represents a number, but "hello" is not a try: valid integer string. Attempting int("hello") raises a ValueError. number = int("hello") The except ValueError as e: block catches except ValueError as e: print("A ValueError occurred:", e) the error and prints a message. AttributeError This exception is raised when an attribute or method is not found on an object, such as trying to access a non-existent attribute of a class instance. AttributeError The string object my_string does not have an append method (which is a method for try: lists). Attempting to call my_string.append(" my_string = "hello" world") raises an AttributeError. my_string.append(" world") except AttributeError as e: The except AttributeError as e: block print("An AttributeError occurred:", e) catches the error and prints a message with details about the issue. IOError This exception is raised when an I/O operation, such as reading or writing a file, fails due to an input/output error. IOError The code attempts to open a file ("non_existent_file.txt") for reading, but the try: file doesn’t exist. This raises an IOError, which is caught by with open("non_existent_file.txt", "r") the except IOError as e: block, and an error as file: content = file.read() message is printed. except IOError as e: print("An IOError occurred:", e) ZeroDivisionError This exception is raised when an attempt is made to divide a number by zero. ZeroDivisionError The code tries to perform 10 / 0, which will raise a ZeroDivisionError because division try: by zero is not allowed. The except ZeroDivisionError as e: block result = 10 / 0 catches the error and prints the exception except ZeroDivisionError as e: print("A ZeroDivisionError occurred:", message. e) ImportError This exception is raised when an import statement fails to find or load a module. ImportError The code tries to import non_existent_module, which doesn't exist, try: raising an ImportError. The except ImportError as e: block catches import non_existent_module the error and prints a message with the except ImportError as e: print("An ImportError occurred:", e) exception details.