Skip to content
  • About
  • CoursesExpand
    • Problem Solving using C Language
    • Mastering Database Management
    • Linux System Administration
    • Linux and Shell Programming
  • Publications
  • Professional Certificates
  • BooksExpand
    • Books Authored
  • Patents
Download CV

try and except

Catching Exceptions

Earlier when we used the input and int functions to read and parse an integer number entered by the user, there was a possibility of error if the user entered something which can’t be parsed into an int. For eg, if the user entered some str instead of an int.

prompt = input("Enter your age\n")
 try:
     print (int(prompt))
 except:
    print('You should have entered a number')

First, the statements inside try block are executed. If everything seems good, it skips the except block and proceeds. If an exception (error) occurs in the try block, Python jumps out of the try block and executes the sequence of statements in the except block.

Handling an error with a try statement is called catching an exception. In the above example, the except statement prints the error message. In general, catching an exception gives us a chance to fix the problem, or try again, or at least end the program correctly.

Instructions

Define a function with name except_func which takes one argument with name num and returns its multiplication with itself. If the argument passed during the function call is not valid for multiplication, return a str with content invalid number.

def except_func(num):
try:
num1=int(num)
return num1*num1
except:
return “invalid number”

Function Call

except_func(“nishant”)

Nishant Munjal

Coding Humanity’s Future </>

Facebook Twitter Linkedin YouTube Github Email

Tools

  • SIP Calculator
  • Write with AI
  • SamplePHP
  • Image Converter

Resources

  • Blog
  • Contact
  • Refund and Returns

Legal

  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

© 2025 - All Rights Reserved

  • About
  • Courses
    • Problem Solving using C Language
    • Mastering Database Management
    • Linux System Administration
    • Linux and Shell Programming
  • Publications
  • Professional Certificates
  • Books
    • Books Authored
  • Patents
Download CV
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok