python try catch

Do you want to know the details regarding “python try catch”. If yes, you’re in the correct tutorial.

python try catch

try:
    someFunction()
except Exception as ex:
    template = "An exception of type 0 occurred. Arguments:\n1!r"
    message = template.format(type(ex).__name__, ex.args)
    print (message)
>>> def catch():
...     try:
...         asd()
...     except Exception as e:
...         print e.message, e.args
... 
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: 0".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
try:
  val = 1/0 
except Exception as e:
  raise Exception('ZeroDivisionError')
try:
    Age = int(input("Your Age:- "))
except ValueError:
    print("Age not in Intger form")
import sys
try:
	S = 1/0 #Create Error
except: # catch *all* exceptions
    e = sys.exc_info()
    print(e) # (Exception Type, Exception Value, TraceBack)

############
#    OR    #
############
try:
	S = 1/0
except ZeroDivisionError as e:
    print(e) # ZeroDivisionError('division by zero')

Final Thoughts

I hope this post helps you to know about “python try catch”. If you have any questions regarding this tutorial please let us know via the comment section. Share this post with your friends and family via social networks.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coder Diksha. Here, I post about programming to help developers.

Share on:

Leave a Comment