Home > OS >  Logging Exceptions Without breaking the code execution in Python
Logging Exceptions Without breaking the code execution in Python

Time:03-08

I'm learning Python and have written a test that accepts user inputs for basic calculations. I'm also attempting to log the exceptions and the outcome in a file. So, I'd like to test my function with any user input, such as str or a special character, and it shouldn't stop the execution. Could someone please look through my code? Thanks in advance!

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s: %(name)s: %(message)s")
logging.basicConfig(filename="arithmetic_test.log", level=logging.DEBUG, format="%(asctime)s: %(name)s: %(message)s")


class Calculator:
    def __init__(self):
        pass

    def add(self, a, b):
        if isinstance(a, int) and isinstance(b, int):
            try:
                logger.debug("\nAdding two integers")
                result = a   b
            except ValueError as e:
                logger.error("\nAddition not allowed by Invalid type")
                raise e
            else:
                return result

    def sub(self, a, b):

        if isinstance(a, int) and isinstance(b, int):
            logger.info("\nSubtracting two integers")
            return a - b
        else:
            logger.info("\nSubtraction not allowed by Invalid type", TypeError)

    def mul(self, a, b):

        if isinstance(a, int) and isinstance(b, int):
            logger.info("\nMultiplying two integers")
            return a * b
        else:
            logger.info("\nMultiplication not allowed by invalid type", TypeError)

    def div(self, a, b):
        try:
            if isinstance(a, int) and isinstance(b, int):
                result = a / b
                logger.info("\nDividing two integers")
        except ZeroDivisionError:
            logger.exception("\n Division not allowed by zero\n")
        except ValueError:
            logger.exception("\n Division not allowed by invalid type\n")
            raise
        else:
            return result


class CalculatorApp:
    calc = Calculator()
    while True:
        print("Please select operation -n"
              "1. Addn"
              "2. Subtractn"
              "3. Multiplyn"
              "4. Dividen")

        # Take input from the user
        select = int(input("Select operations form 1, 2, 3, 4 :"))

        number_1 = int(input("Enter first number: "))
        number_2 = int(input("Enter second number: "))

        if select == 1:
            print(number_1, " ", number_2, "=", calc.add(number_1, number_2))

        elif select == 2:
            print(number_1, "-", number_2, "=", calc.sub(number_1, number_2))

        elif select == 3:
            print(number_1, "*", number_2, "=", calc.mul(number_1, number_2))

        elif select == 4:
            print(number_1, "/", number_2, "=", calc.div(number_1, number_2))
        else:
            print("Invalid input")
            break

CodePudding user response:

I think you defined an exception with ValueError, but you are tryingt o raise TypeError, along with raise lines. Could you try changing TypeError into ValueError and remove raise lines?

CodePudding user response:

Include code under # Take input from the user in a try except block, as you are taking input and trying to convert it to integer directly this gives the exception as any non-numeric character can't be converted to an integer


class CalculatorApp:
    calc = Calculator()
    while True:
        print("Please select operation -n"
              "1. Addn"
              "2. Subtractn"
              "3. Multiplyn"
              "4. Dividen")

        try:
            # Take input from the user
            select = int(input("Select operations form 1, 2, 3, 4 :"))

            number_1 = int(input("Enter first number: "))
            number_2 = int(input("Enter second number: "))

            if select == 1:
                print(number_1, " ", number_2, "=", calc.add(number_1, number_2))

            elif select == 2:
                print(number_1, "-", number_2, "=", calc.sub(number_1, number_2))

            elif select == 3:
                print(number_1, "*", number_2, "=", calc.mul(number_1, number_2))

            elif select == 4:
                print(number_1, "/", number_2, "=", calc.div(number_1, number_2))
            else:
                print("Invalid input")
                break
        except Exception as e:
            print(str(e))

  • Related