Python provides exception handling through the >>> outputFile = open('foam.txt')
If the file does not exist, the statement fails, and Python displays the following error message: >>> outputFile = open('foam.txt')
Traceback (innermost last):
File "<stdin>", line 1, in ?
IOError: (2, 'No such file or directory')
If you use exception handling, you can catch the error, display a helpful message, and take the appropriate action. For example, a revised version of the code attempts to open the same file within a >>> try:
... outputFile = open('foam.txt')
... except IOError as error:
... print('Exception trapped: ', error)
...
Exception trapped: (2, 'No such file or directory')
You can raise your own exceptions by providing the error type and the error message to the def myFunction(x,y):
if y == 0:
raise ValueError('y argument cannot be zero')
else:
return x/y
try:
print(myFunction(temperature, velocity))
except ValueError as error:
print(error)
Exception handling is discussed in more detail in Error handling in the Abaqus Scripting Interface. | |||||||