Change language

try it except in Python

| |

try () is used in handling errors and exceptions
There are two types of errors:

  • Syntax error : Also known as parsing errors, the most basic. Thrown when the Python parser cannot understand a line of code.
  • Exception : Errors encountered during runtime. for example — ZeroDivisionError.

List of exceptional errors:

  • IOError: if the file cannot be opened
  • KeyboardInterrupt: when the user presses an unnecessary key
  • ValueError: when an inline function receives an invalid argument
  • EOFError: if the end of the file is deleted without reading any data
  • ImportError: if the module cannot be found

Now we have the task of handling these errors in our Python code. So here we need to try — except statements.

  Basic Syntax:  try: // Code except: // Code 

How does try () work?

  • The try clause is executed first, i.e. the code between the try clause and the exception .
  • If there are no exceptions, then only the try , clause will be executed, except the clause is completed.
  • If a any exception, the try offer will be skipped and will be executed, except the offer.
  • If any exception occurs, but the exceptions offer in the code does not handle it, it is passed to external try statements. If the exception is not handled, execution stops.
  • The try statement may contain more than one sentence, except for

Code 1: No exceptions, so try will be executed.

# Python code for illustration
# try () work

def divide (x, y):

try :

  # Gender department: gives only fractional part as response

result = x / / y

  print ( "Yeah! Your answer is: " , result)

  except ZeroDivisionError:

  print ( "Sorry! You are dividing by zero" )

 
# Look at the parameters and notice how the program works

divide ( 3 , 2 )

Output:

 (’Yeah! Your answer is:’, 1) 

Code 1: Exists exception, so only for the exception clause will work.

# Python code for illustration
# try () work

def divide (x, y):

try :

# Gender department: gives only fractional part as answer

result = x / / y

print ( " Yeah! Your answer is: " , result)

  except ZeroDivisionError:

  print ( "Sorry! You are dividing by zero" )

 
# Look at the parameters and notice how the program works

divide ( 3 , 0 )

Output:

 Sorry! You are dividing by zero 

Related Articles:

  • Shop

    Learn programming in R: courses

    $

    Best Python online courses for 2022

    $

    Best laptop for Fortnite

    $

    Best laptop for Excel

    $

    Best laptop for Solidworks

    $

    Best laptop for Roblox

    $

    Best computer for crypto mining

    $

    Best laptop for Sims 4

    $

    Latest questions

    NUMPYNUMPY

    Common xlabel/ylabel for matplotlib subplots

    12 answers

    NUMPYNUMPY

    How to specify multiple return types using type-hints

    12 answers

    NUMPYNUMPY

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    12 answers

    NUMPYNUMPY

    Flake8: Ignore specific warning for entire file

    12 answers

    NUMPYNUMPY

    glob exclude pattern

    12 answers

    NUMPYNUMPY

    How to avoid HTTP error 429 (Too Many Requests) python

    12 answers

    NUMPYNUMPY

    Python CSV error: line contains NULL byte

    12 answers

    NUMPYNUMPY

    csv.Error: iterator should return strings, not bytes

    12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically