PROG1925 Programming Concepts I - Errors and Exceptions PDF

Document Details

AffordableHarpy8960

Uploaded by AffordableHarpy8960

Conestoga College

Tags

programming concepts errors and exceptions python exceptions programming

Summary

This document is a course note on programming concepts I. It covers errors and exceptions that can happen in a program, try-except blocks, how to raise exceptions and exception handling.

Full Transcript

PROG1925 Programming Concepts I Errors and Exceptions Week Topic Errors and Exceptions o Errors o Exceptions o try-except Block o finally Block o Raising Exceptions o Exceptions Across Functions Errors – Why are they a concern? ▪ Errors can and do occur at any stage when a pr...

PROG1925 Programming Concepts I Errors and Exceptions Week Topic Errors and Exceptions o Errors o Exceptions o try-except Block o finally Block o Raising Exceptions o Exceptions Across Functions Errors – Why are they a concern? ▪ Errors can and do occur at any stage when a program runs ▪ It is impossible to anticipate every error that may occur ▪ Users are famously unpredictable and will use programs in ways not anticipated ▪ You may encounter errors that are not the fault of your application or code ▪ Interactions with other software ▪ Interactions with different hardware/platforms ▪ Etc. 3 Exceptions – What are they? ▪ An exception is a type of error that stops the execution of a program during run time ▪ For example, if a program is trying to add numbers but one of those numbers is a string ▪ Modern object-oriented programming languages, (including Python), have systems in place to handle exceptions 4 Exceptions ▪ It would be extremely cumbersome and time consuming if we had to check for errors on each statement ▪ Python allows us to separate the error-handling code from the primary logic code of our applications using exceptions and exception handlers ▪ This is primarily done through a series of try and except blocks of code 5 try-except Block – How they work ▪ Code within a try block is executed normally ▪ If no exception occurs, any except blocks are ignored ▪ If an exception occurs, execution immediately leaves the try block and goes to an except block ▪ One or more except blocks proceed a single try block ▪ An except handler captures and handles generic exceptions or a specific type of exception ▪ The exception can optionally be assigned to a variable to access information about it 6 try-except – Example ▪ The code to the right takes 2 inputs try: and casts them as int values to be a = int(input("enter a value: " )) b = int(input("enter a value: " )) added and the result displayed answer = a + b ▪ All that code is nested in the try block print(f"{a} + {b} = {answer}") except Exception: print("Something went wrong") ▪ In this example the user entered a ‘t’ instead of an integer for the second value, causing an exception when ---OUTPUT--- enter a value: 4 the code tries to cast the input to an enter a value: t int, which in turn caused the Something went wrong program to jump into the except block and show the error message 7 try-exempt – Specific Exceptions ▪ In the previous example a general Exception was caught ▪ It is possible to catch many different types of exceptions, allowing you to create code that is specific to each one ▪ Some other types of exceptions that can be caught are: ValueError, TypeError, ZeroDivisionError, IndexError, IOError, etc. NOTE: The order except blocks are created matters as Python check them in order, so if the generic except block comes first it will catch the error before any specific exception blocks that may come later 8 try-except – Specific Exceptions Example try: ▪ This example is like the previous, but a = int(input("enter a value:" )) instead of adding it’s dividing, and b = int(input("enter a value:" )) answer = a / b there are now 3 except blocks print(f"{a} / {b} = {answer}") except ZeroDivisionError: ▪ The ZeroDivisionError exception block print("Can't divide by 0") runs when b = 0 except ValueError: print("Input must be an integer") except Exception: ▪ The ValueError exception block runs print("Something went wrong") when the input is not an int ---OUTPUT--- ▪ The Exception exception block runs enter a value: 4 when the exception is not a specific enter a value: t exception already accounted for Something went wrong 9 try-exempt – Exception Order ▪ If an exception matches multiple exceptions the code will use the first except block that matches, so order matters ▪ Always place the most specific type of exception first ▪ The general Exception block will trap every possible exception that can occur ▪ The Exception block should always be the last except block to catch any exceptions not anticipated ▪ This is like an else block in an if statement 10 finally Block – How they work ▪ If an exception occurs, flow of the program will resume outside the try and except blocks ▪ An important statement within the try may be missed ▪ The finally block, (which is optional), is guaranteed to execute, regardless of whether an exception occurs within a try block ▪ Particularly useful when dealing with the release of resources 11 finally Block – Example try: result = x / y print(f"Result: {result}") ▪ In this example the division except ZeroDivisionError: operation will either be successful print("Error: Division by zero") and displayed to the output, or an except TypeError: exception may occur print("Error: Unsupported operation") finally: print("Division complete") ▪ Regardless of whether the try block completes successfully or not, the finally block will always run --- OUTPUT for x = 10, y = 2 --- Result: 5.0 Division complete ▪ Note in the output how the finally block causes the “Division complete” --- OUTPUT for x = 10, y = "g" --- message to always show Error: Unsupported operation Division complete 12 Exceptions – Raising Exceptions ▪ There are times when an exception does not occur, however, it makes logical sense for one to happen ▪ In Python we can trigger an exception manually by using the keyword raise, (raising an exception) ▪ You may want to do this to signal an error condition, such as out of range values ▪ Raising an exception does not need to be done in a try block, unless it is also associated with an except block ▪ When you raise an exception, you need to state what exception you are raising 13 Exceptions – raise Example try: age = int(input('Enter age, (16-80): ')) ▪ The program gets an age if age < 16 or age > 80: from the user raise ValueError ▪ If the age falls in the print(“Welcome member") acceptable range, it welcome # further code here the user to the program except ValueError: ▪ If the age is not acceptable, print(f'{age} is not an eligible age') execution of the program is halted by raising a ValueError ---POSSIBLE OUTPUTS--- exception Enter age, (16-80): 19 Welcome member Enter age, (16-80): 4 4 is not an eligible age 14 Exceptions – raise Example try: coin = input("Pick Heads or Tails") ▪ When raising an exception, it match coin: is possible to also pass a case "Heads" | "Tails" : message to the exception print(f"You picked: {coin}") case _: ▪ This is done by adding a raise Exception("Try again") string literal as an argument except Exception as e: to the exception print(e) ▪ If you then capture the ---POSSIBLE OUTPUT--- Exception into an object, you Pick Heads or Tails: Heads can display its message to You picked: Heads the output Pick Heads or Tails: Shiny Try again 15 Exceptions – Exceptions Across Functions def test_function(test_param): print("start function") ▪ Take a look at this example if test_param == 12: raise Exception() ▪ What statements do you think will print to output? print("end function") ▪ Notice that an exception is value = 12 raised in the function try: ▪ What will happen to the print("try - first statement") test_function(value) execution of this program if it print("try - last statement") is thrown? except Exception as ex: print("an exception") finally: print("finally") print("last - statement") 16 Exceptions – Exceptions Across Functions def test_function(test_param): ---OUTPUT--- print("start function") try - first statement if test_param == 12: start function raise Exception() an exception finally print("end function") last - statement value = 12 try: print("try - first statement") test_function(value) print("try - last statement") except Exception as ex: print("an exception") finally: print("finally") print("last - statement") 17 Thank you If you have any questions, please make sure to contact your instructor or to utilize one of the school provided resources available to you.

Use Quizgecko on...
Browser
Browser