Quick actions

cmd+k|ctrl+k

Navigation

Languages

Python Web-L06 (try...except..)

Snippet info

Language

Python

Visibility

public

Author

victormakwaitat

Created

2025-02-11T04:23:06.805285Z

Updated

2025-02-12T09:08:25.832728Z

a = 10
b = 0

try:
    result = a/b
except ZeroDivisionError:
    print("data error")
except TypeError:
    print("check data type")
finally: # finally statement -> protect data files
    print("this line will run not matter what !")
    
a = 10
b = 'a'

try:
    result = a/b
except ZeroDivisionError:
    print("data error")
except TypeError:
    print("check data type")
finally: # finally statement -> protect data files
    print("this line will run not matter what !")
    
# case 3
a = -2
b = 2

while a < 3:
    print('------------')
    a+=1
    b-=1
    try:
        res = a / b
    except ZeroDivisionError:
        print('{0}, {1} - division by 0'.format(a,b))
        res = 0
        continue
    finally:
        print('{0}, {1} - always executes'.format(a,b))
        
# case 4
a = 0
b = 2

while a < 3:
    print('------------')
    a+=1
    b-=1
    try:
        res = a / b
    except ZeroDivisionError:
        print('{0}, {1} - division by 0'.format(a,b))
        res = 0
        break
    finally:
        print('{0}, {1} - always executes'.format(a,b))
        
# case 5
a = 3
b = 2

while a < 3:
    print('------------')
    a+=1
    b-=1
    try:
        res = a / b
    except ZeroDivisionError:
        print('{0}, {1} - division by 0'.format(a,b))
        res = 0
        continue
    finally:
        print('{0}, {1} - always executes'.format(a,b))
else:
    print('\n\nno errors were encountered!')
    
# case 6
a = 0
b = 5

while a < 3:
    print('-----case 6-------')
    a+=1
    b-=1
    try:
        res = a / b
    except ZeroDivisionError:
        print('{0}, {1} - division by 0'.format(a,b))
        res = 0
        continue
    finally:
        print('{0}, {1} - always executes'.format(a,b))
    print('{0}, {1} - main loop'.format(a,b))
else:
    print('\n\nno errors were encountered!')
INFO