Home » Python

try keyword with example in Python

Python try keyword: Here, we are going to learn about the try keyword with example.
Submitted by IncludeHelp, on April 15, 2019

Python try keyword

try is a keyword (case-sensitive) in python, it is a part of "try...except" block, it is used to define a block (of coding statements) to test/check whether this block contains an exception or not. If try block contains an exception program's control moves to the except block.

Syntax of try keyword

    try:
        statement(s)-1
    except:
        statement(s)-2

While executing the statement(s)-1, if there is any exception raises, control jumps to except block and statement(s)-2 executes.

Example:

    Input:
    a = 10
    b = 0

    try:
        # no error
        result = a%b
        print(result)
    
    except:
        print("There is an error")

    Output:
    There is an error

Python examples of try keyword

Example 1: Find modulus of two number and handle exception, if divisor is 0.

# python code to demonstrate example of 
# try, except keyword  

# Find modulus of two number and 
# handle exception, if divisor is 0

a = 10
b = 3

try:
    # no error
    result = a%b
    print(result)
    
    # assign 0 to b
    # an error will occur
    b = 0
    result = a%b
    print(result)
    
except:
    print("There is an error")

Output

1
There is an error





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.