How can I properly handle exceptions in my Python program?

  • Thread starter rawen
  • Start date
  • Tags
    Python
In summary: Thank you very much.In summary, the conversation is about a user who is learning Python and is stuck on an exercise involving creating a program to calculate the position of an object. The program is supposed to take in parameters from the command line and handle exceptions if the parameters are not given. The user receives help from others in the community and is able to get the program working.
  • #1
rawen
6
0
Code:
Hello, dear PFers. I'm currently beginning to learn Python and I got stuck at one exercise.

Homework Statement


Basically, I'm supposed to create a simple program that will calculate the position of an object according to the formula y(t) = v0*t - 0.5*g*t**2. Parameters v0 and t are supposed to be read from the command line and if one of them, or both are not given, the program should ask for them via an exception.


Homework Equations



The Attempt at a Solution


----------------------------------------------------------------
Code:
import getopt, sys
g = 9.81
options, args = getopt.getopt(sys.argv[1:], '',['v0=', 't='])
try:
    for option, value in options:
        if option == '--t':
            t = float(value)
        elif option == '--v0':
            v0 = float(value)
  
except:
    if '--t' not in options:
        t = raw_input('t= ?')
        t = float(t)
    elif '--v0' not in options:
        v0 = raw_input('v0= ?')
        v0 = float(v0)
       
y = v0*t - 0.5*g*t**2
print 'y=', y, 'm'
----------------------------------------------------------------

It apparently works if I provide a valid input on a command line, but if I omit one of the parameters, the program is terminated with NameError: name 'v0' is not defined (for example). It completely ignores my except block. I'm new to this so it may be a bit silly, but I'm thankful in advance for any help.
 
Last edited:
Technology news on Phys.org
  • #2
The best I can do is point you to some documentation on python exceptions - http://docs.python.org/tutorial/errors.html.

I'm not at all familiar with python and how it handles exceptions, but I believe your code needs to raise an exception, probably a custom exception that you design. See sections 8.4 and 8.5 at the above link.

Hope that helps.
 
  • #3
When you say
if I omit one of the parameters,
do you mean when you invoke the code as, for example, prog --t --v 3
where you have forgotten to supply the value for the t parameter?
Or do you mean, for example, prog --v 3 where you have forgotten the --t 10 pair?

Are you building your program to accommodate both mistakes? As written, it doesn't.
 
Last edited:
  • #4
NascentOxygen said:
When you say do you mean when you invoke the code as, for example, prog --t --v 3
where you have forgotten to supply the value for the t parameter?
Or do you mean, for example, prog --v 3 where you have forgotten the --t 10 pair?

Are you building your program to accommodate both mistakes? As written, it doesn't.

Yes, I'm aware of that. Writing prog --t --v 3 would result in a GetoptError, but I do not need to accommodate this mistake into the program. For now I'm concerned about prog --v 3 or prog --t 3 or only prog cases
 
  • #5
Hi rawen. You are imagining an error condition where python will see none. Although python is powerful, it can't yet read minds. :smile:

Code:
     for option, value in options:
        if option == '--t':
            t = float(value)
        elif option == '--v0':
            v0 = float(value)

This statement will execute properly whether or not --t and --v0 are present. An if statement is not in error just because no match was found. So, python is content to execute this statement and has no reason to execute your except: block.

If you are determined to use the try: except: approach then you could experiment with deliberately creating an error condition, e.g.,

Code:
        if option == '--t':
            t = float(value)
        elif option == '--v0':
            v0 = float(value)
        else v0 = 0/0
I don't have python at hand to try this out, but it won't like dividing by zero. To give this a more polished appearance, I reckon if you look you'll probably find python has a built-in statement to raise an exception (I haven't used python for a while) and force a jump into your except: code.

In a short program it may be tidier to do away with the except: statement and incorporate its block of code into your if statement as a further else block, though it seems the specification for your assignment wants you to employ python's except: technique.
 
Last edited:
  • #6
Hello, thanks for all the help guys. I've managed to get the program working.
This statement will execute properly whether or not --t and --v0 are present. An if statement is not in error just because no match was found. So, python is content to execute this statement and has no reason to execute your except: block.
I now see what I did wrong. Your post was especially helpful, Nascent.
 

1) What is an exception in Python?

An exception in Python is an error that occurs during the execution of a program. It can happen due to various reasons such as invalid input, syntax errors, or runtime errors. When an exception occurs, the program stops running and displays an error message.

2) How do you handle exceptions in Python?

To handle exceptions in Python, you can use the try-except statement. The code that may cause an exception is placed inside the "try" block, and the code to handle the exception is placed inside the "except" block. This ensures that the program continues to run even if an exception occurs.

3) What is the purpose of the "finally" block in exception handling?

The "finally" block is used to execute a set of code, regardless of whether an exception occurs or not. It is often used to perform cleanup operations such as closing files or database connections. The "finally" block is executed after the "try" and "except" blocks, even if an exception is raised.

4) Can you have multiple except blocks for a single try block?

Yes, you can have multiple except blocks for a single try block in Python. This allows you to handle different types of exceptions separately. It is important to place the most specific exception first and the most general exception last in the except blocks.

5) How do you create custom exceptions in Python?

You can create custom exceptions in Python by creating a new class that inherits from the "Exception" class. You can add custom attributes and methods to this class to make it more specific and useful for your program. Then, you can raise instances of this custom exception class using the "raise" keyword.

Similar threads

  • Programming and Computer Science
Replies
2
Views
905
  • Programming and Computer Science
2
Replies
55
Views
4K
  • Programming and Computer Science
Replies
2
Views
16K
Replies
11
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Programming and Computer Science
Replies
8
Views
888
Replies
2
Views
1K
  • Programming and Computer Science
Replies
5
Views
3K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
Back
Top