Blog Detail

September 3, 2023

Python Exception Handling Exercises

  • Why do we use exception handling ?



  • What is the output of this code?

                    try:    
        num = int("$10")
        print(num)
    except ValueError:
        print("An exception occurred. Invalid conversion to an integer!")
  • What is the output of this code?

                    try:    
        x = 10 / 0
        print(x)
    except ZeroDivisionError:
        print("An exception occurred: Division by zero!")
  • What is the output of this code?

                    try:
        num_list = [1, 2, 3]
        print(num_list[3])
    except:
        print("An exception occurred: Index out of range.")
  • What is the output of this code?

                    try:
        num_list = [1, 2, 3]
        print(num_list[0])
    except:
        print("An exception occurred: Index out of range.")
    
  • What is the output of this code?

                    try:
        x = str("123")
        print(x)
    except:
        print("An exception occurred: Invalid conversion to a string.")
  • What is the output of this code?

                    try:
        x = str("123")    
    except:
        print("An exception occurred: Invalid conversion to a string.")
    else:
        print(x)
    
  • What is the output of this code?

                    try:
        x = int("5")    
    except:
        print("An exception occurred!")
    else:
        x = x * 2
        print(x)
  • What is the output of this code?

                    try:
        x = int("5")    
    except:
        print("An exception occurred!")
    else:
        x = x * 2
        print(x)
    finally:
        print("Execution completed!")
  • What is the output of this code?

                    try:
        x = int("5.0")    
    except:
        print("An exception occurred!")
    else:
        x = x * 2
        print(x)
    finally:
        print("Execution completed!")
  • Python Exercises for Exception Handling


    You can also share ‘Python Exception Handling’ Exercises on your:
    X (Twitter)TelegramLinkedinFacebook – or on your favorite platform…




    Happy Coding!
    Behnam Khani