Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with try and except in python?

This program has to analyze student numbers and if they are correct write them to one list and if not write them to another list. They are correct if they have eight digits and contain only numbers.

I however have no idea what to type when it comes to the try and except part.

If anyone could help, I would greatly appreciate it!

Valid_file = "ValidNumbers.txt"
Invalid_file = "InvalidNumbers.txt"
Data_file = "Data.txt"

def analyse_students(Data_file):
    lenth = len(Data_file)
    total = 0
    try:
    
    except: 
    
    return 0
    
def read(Data_file):
    count = 0
    student_list = []
    try:
        open(Data_file)
    except:
        print("Couldn't append file", Valid_file)
    return count, student_list

def write(student, status):
    if status:
        try:
            open(Data_file)
        except:
            print("Couldn't append file", Invalid_file)
    
count, student_list = read(Data_file)

print("Number of lines read", count)

for student in student_list:

    print("See output files")
like image 682
Pieter Booysen Avatar asked Feb 22 '26 19:02

Pieter Booysen


1 Answers

Okey, so there a few things that need to be explained where.

What is try-except used for?

It is used for catching errors raised by the program. Any code susceptible of raising an exception is inserted inside a try statement, and below that statement, any number of except statements with any single error that you want to catch.

try:
    user_input = int(input('Give me a number: '))
except ValueError:
    print('That is not a number!')

When should i use try-except?

It is not a good practice to use a try-except on every single line of code that could raise an error, because that may be half of it, or more. So when shall you use it? Simple, ask this question: Do I want to do any custom action with that error being raised? If the answer is yes, you are good to go.

Catching Exception or empty except

As I see in your example, you are using an empty except. Using an empty except statement will catch every single error raised that the surrounded code, which is similar (but not the same) as catching Exception. The Exception class is the superclass of every single built-in exception in the Python environment that are non-system-exiting (read here) and its generally a bad practice to catch either all exceptions with except: or Exception with except Exception:. Why? Because you are not letting the user (or even you, the programmer) know what error you are handling. For example:

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except Exception:
    print('Error!')
    # But wait, are you catching ValueError because the user did not input a number, 
    # or are you catching IndexError because he selected an out of bound array index? 
    # You don't know  

Catching multiple exceptions

Based on the previous example, you can use multiple try-except statements to difference which errors are being raised.

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except ValueError:
    print('That is not a number')
except IndexError:
    print('That fruit number does not exist!')  

Grouping exceptions

If there are two particular exceptions that you want to use for a same purpose, you can group them in a tuple:

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except (ValueError, IndexError):
    print('Invalid selection!')  

Your case

Based on this information, add those try-except blocks to your code, and see what possible errors that could be raised during its execution, asking the previously recommended question Do I want to execute some custom action with this error?

Additionally

  • There are try-except-else statements. See here
  • There are try-except-finally statements. See here
  • You can combine them all in a try-except1-except2...exceptN-else-finally statement.
  • I recommend you get familiar with built-in errors why practicing this!
like image 86
Cblopez Avatar answered Feb 24 '26 09:02

Cblopez