PythonPlaza - Python & AI

Python

IntroductionVariablesIf-else
Strings Functions while-loop
For-LoopListSet
DictionaryTuple Try..Except
Class/ObjectInheritancePolymorphism
File Handling

Python try-except

The try/except is widely used in Python applications and software development. Using try/except we can handle any errors in the application and catch the errors so that the application does not break or throw an unfriendly error message on the screen. Here's the syntax for try/except. The else block gets executed when there is no error. The finally block always gets executed even when there is an error or no error.
try:
block of code
except:
do something when there is an error
else:
execute code when there is no error
finally:
always execute this code

Let's see some examples of try-except



Code Example 1:
#Variable A is not assigned any value
try:
  print(A)
except:
  print("An exception occurred")

#Output:
An exception occurred

Code Example 2:
#Variable B is not assigned any value.
try:
  print(B)
except:
  print("An exception occurred")
else:
  print("There is no error")
finally:
  print("Executing the finally block")

#Output:
An exception occurred
Executing the finally block

try-except with Exception message

Sometimes it is necessary to get the Exception message, so that you can store the exception in a database or send out an email to the developers about the error in the application. This is one of the best practices of software development where data related errors can be caught before they display errors to the users. The exception messages can also be logged. In the following example, the code in try will cause an exception because the input_number2 is entered as 0. Any number divided by 0 will give an exception. This will execute the except black and will execute the finally block.



Code Example 3:
#Code that can raise an exception
try:
    input_number1 = int(input("Enter a number less than 100 "))
    input_number2= int(input("Enter a number less than 10 "))
    input_result = input_number1  / input_number2
    print(f"The result is: {input_result}")
except Exception as e:
    # Handle any other unexpected exceptions
    print(f"An unexpected error occurred: {e}")
else:
    # This is executed if no exceptions occurred
    print("Division successful.")
finally:
    # Always executed
    print("Execution finished.")

#Output:
Enter a number less than 100 12
Enter a number less than 10 0
An unexpected error occurred: division by zero