Python Tutorial for Beginners - 12. Using Try/Except Blocks for Error Handling

Table of Contents

  1. Test file
  2. Currupt file
  3. Run Code 1 in Python
  4. Run Code 2 in Python
  5. Run Code 3 in Python
  6. Run Code 4 in Python
  7. Run Code 5 in Python
  8. Run Code 6 in Python
  9. Run Code 7 in Python
  10. Run Code 8 in Python
  11. Run Code 9 in Python
  12. Run Code 10 in Python
  13. Run Code 11 in Python

Test file

1
Test File Contents!

test_file.txt

Currupt file

1
Currupt File!

currupt_file.txt

Run Code 1 in Python

1
2
3
4
5
6
7
8
try:
     pass
except Exception:
    pass
else:
   pass
finally:
   pass

start.py

Run Code 2 in Python

1
2
3
4
5
6
f = open('testfile.txt')

try:
     pass
except Exception:
    pass

start.py

Run Code 3 in Python

1
2
3
4
try:
    f = open('testfile.txt')
except Exception:
    print('Sorry. This file doenst exist')

start.py

Run Code 4 in Python

1
2
3
4
5
try:
    f = open('test_file.txt')
    var = bad_var
except FileNotFoundError:
    print('Sorry. This file doenst exist')

start.py

Run Code 5 in Python

1
2
3
4
5
6
7
try:
    f = open('test_file.txt')
    var = bad_var
except FileNotFoundError:
    print('Sorry. This file doenst exist')
except Exception:
    print('Sorry. Samting went wrong')

start.py

Run Code 6 in Python

1
2
3
4
5
6
try:
    f = open('testfile.txt')
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(e)

start.py

Run Code 7 in Python

1
2
3
4
5
6
7
8
9
try:
    f = open('test_file.txt')
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(e)
else:
   print(f.read())
   f.close()

start.py

Run Code 8 in Python

1
2
3
4
5
6
7
8
9
10
11
try:
    f = open('test_file.txt')
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(e)
else:
   print(f.read())
   f.close()
finally:
   print('Excecuting Finally...')

start.py

Run Code 9 in Python

1
2
3
4
5
6
7
8
9
10
11
try:
    f = open('testfile.txt')
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(e)
else:
   print(f.read())
   f.close()
finally:
   print('Excecuting Finally...')

start.py

Run Code 10 in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
try:
    f = open('curruptfile.txt')
except IOError as e:
    print('First!')
except Exception as e:
    print('Second')
else:
    print(f.read())
    f.close()
finally:
    print("Executing Finally...")

print('End of program')

start.py

Run Code 11 in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try:
    f = open('curruptfile.txt')
    # if f.name == 'currupt_file.txt':
    #     raise Exception
except IOError as e:
    print('First!')
except Exception as e:
    print('Second')
else:
    print(f.read())
    f.close()
finally:
    print("Executing Finally...")

print('End of program')

start.py


© 2018 - Milovan Tomašević. All rights reserved.

Powered by MT v8.3.0