Home » Learn Python » Exceptions » Catching Specific Exceptions

Catching Specific Exceptions

If it’s possible that some code may raise multiple different exceptions, we can catch the different types of exception separately.

In this example, f_to_c() raises our custom NoInputError if no input is entered, or ValueError if input is entered but can’t be converted to a number.

class NoInputError(Exception):

def f_to_c(temperature_f):

    # Check for zero length string
    if not temperature_f: 
        raise NoInputError("No input")

    # The cast to float will raise a ValueError
    # if the string can't be converted to a float.
    return (float(temperature_f) - 32) * 5/9

def main():
    temperature_f = input("Enter a temperature in Fahrenheit: ")

        temperature_c = f_to_c(temperature_f)
        print(f"{temperature_f} F is {temperature_c:.2f} C")
    except NoInputError:
        print("No input entered.")
    except ValueError:
        print("Input cannot be converted to a number.")

Output if no input entered:
No input entered.
Output if text entered which cannot be converted to a number:
Input cannot be converted to a number.
Output if 97 entered:
97 F is 36.11 C

Leave a Reply

Blog at WordPress.com.