BaseException. However, if you create
your own exception class, you should derive it from the
class Exception.
raise ArithmeticError() throw new ArithmeticException() \_____________________/ \_____________________________/ how to "throw" in Python how to do the analogous thing in Java
| Python version | Java version |
try:
foobar()
except ArithmeticError as ae:
print(ae) |
try {
foobar();
} catch(ArithmeticError ae) {
System.out.println(ae);
} |
Copy the following code into a python program ex0.py.
TODO Find inputs that, when you run the program, cause:
Copy the following code into a python program ex1.py
and use chmod to make it executable (so you can run it as
./ex1.py).
Note: sys.argv is a list of the
command-line arguments, where sys.argv[0] is the
program (e.g. "./ex1.py" in this case).
TODO
./ex1.py 50,10,90
Shouldn't have any exceptions./ex1.py 50,-10,90 Exception type:___________./ex1.py 50,one,90 Exception type:___________./ex1.py 50,0,90 Exception type:___________./ex1.py Exception type:___________print(getSF(sys.argv[1].split(",")))
in a try with except clauses, make the program so that it
prints the following output for the following inputs:
$ ./ex1.py 50,10,90 20 $ ./ex1.py 50,-10,90 Error! there was a problem $ ./ex1.py 50,one,90 Error! there was a problem $ ./ex1.py 50,0,90 Error! no zeros allowed $ ./ex1.py Usage: ./ex1.py <numlist>
$ ./ex1.py 50,-10,90 Error in compute function! $ ./ex1.py 50,one,90 Error! non-numeric in argument listMake it happen! However, you are *not* allowed to print anything out in the compute function! Instead, create your own exception class, and raise an exception in compute() if you try to take the sqrt of a negative. You can catch this exception back in the main block of your code with the other catches to print the appropriate message.
$ ./sol3.py ,34,12 Error! not a comma-separated list $ ./sol3.py 34,,12 Error! not a comma-separated list $ ./sol3.py 34,12, Error! not a comma-separated list $ ./sol3.py 34,sdf,16 Error! element 'sdf' not an integer
Important! It should still be the case that error messages are only printed in except-clauses for the try-block in the main block at the end.
arg2list(arg)
that takes a string that is a comma-separated list (like the
argument we are expecting)
and splits it into an array of strings, which are the values (no
commas!). Then change the
existing line print(getSF(arg2list(sys.argv[1])))
into:
^[^,]+(,[^,]+)*$
^ matches the beginning of
the string.$ matches the and of
the string.[^,] matches anything *but* a comma.
print(getSF(arg2list(sys.argv[1])))arg2list should check for proper comma-separation, but *not* for the values being numbers! After all, we might want to use arg2list in other situations where comma-separated lists are a thing. I suggest using regular expressions! (see note).