Sometimes programming, that you can do everything you can to make your program user friendly. Unfortunately, this does not mean that the users will be friendly in return.
Errors can occur that will cause your program to fail. So, you need to know how to handle these errors.
Setting It Up
If you have a line in your program, you can set it up for error management. Keep in mind that you may have other ways to check for errors before the error management occurs, but it can still be handy.
For instance, if you plan on opening a file, you can check that the file exists before opening it. If you open a file for reading and it doesn't exist, you get an error. But, let's look at error management methods. The methods is as follows:
In the basic listing, any error that occurs on the 'try' command will cause the 'except' commands to be run.
For example, we could run a division command and if we get a number from the user to perform division on, we would accidentally divide by zero, have the user enter a letter and not a number. There can be more that one cause for an error. By using the 'except' method, we catch all errors and have to deal with them as one issue. We'll cover the individual issues soon.
Let's say we open a file for reading. If the file does not exist, then we will generate an error. We should look at an example:
The 'finally' section is optional and in this case, I do not need it. What happens in the code is that we open a file for reading. If any error occurs, such as the file doesn't exist, then we go through the 'except' code. Here, we open the file for writing. If the file does not exist, it is created. We then close the file and open it again for reading.
I've mentioned that there can be more than one error caused by any command. In the above example, with opening a file and it not existing, the error could have been a permission error and the code in 'except' would not fix it.
Individual Errors
So what other errors can exist? Let me give a sample list:
If you want to handle each error individually, then you can specify the error name, as listed above, after the 'except' word. An example follows:
If the file was not found, we created it. If we by chance specified an incorrect folder name, then we are told so.
If an error is elusive to find the proper name, you can use the code:
The code will print out the same code as listed in the list above for you to use in your code for an exception.
Conclusion
Look at the same code I gave. Try to cause a few errors of your own and trap the error and resolve it, like I did with the 'FileNotFoundError'.
Keep in mind about any code that may cause issues and trap the error so you can resolve it.
Errors can occur that will cause your program to fail. So, you need to know how to handle these errors.
Setting It Up
If you have a line in your program, you can set it up for error management. Keep in mind that you may have other ways to check for errors before the error management occurs, but it can still be handy.
For instance, if you plan on opening a file, you can check that the file exists before opening it. If you open a file for reading and it doesn't exist, you get an error. But, let's look at error management methods. The methods is as follows:
Code:
try:
<command that may fail>
except:
<commands to perform if a failure occurs>
finally:
<commands to run no matter if the 'try' command fails or succeeds>
In the basic listing, any error that occurs on the 'try' command will cause the 'except' commands to be run.
For example, we could run a division command and if we get a number from the user to perform division on, we would accidentally divide by zero, have the user enter a letter and not a number. There can be more that one cause for an error. By using the 'except' method, we catch all errors and have to deal with them as one issue. We'll cover the individual issues soon.
Let's say we open a file for reading. If the file does not exist, then we will generate an error. We should look at an example:
Code:
try:
file1 = open("/home/jarret/test.txt")
except:
file1 = open("/home/jarret/test.txt","w")
file1.close()
file1 = open("/home/jarret/test.txt","r")
The 'finally' section is optional and in this case, I do not need it. What happens in the code is that we open a file for reading. If any error occurs, such as the file doesn't exist, then we go through the 'except' code. Here, we open the file for writing. If the file does not exist, it is created. We then close the file and open it again for reading.
I've mentioned that there can be more than one error caused by any command. In the above example, with opening a file and it not existing, the error could have been a permission error and the code in 'except' would not fix it.
Individual Errors
So what other errors can exist? Let me give a sample list:
- ArithmeticError
- AssertionError
- AttributeError
- BaseException
- BaseExceptionGroup
- BlockingIOError
- BrokenPipeError
- BufferError
- BytesWarning
- ChildProcessError
- ConnectionAbortedError
- ConnectionError
- ConnectionRefusedError
- ConnectionResetError
- DeprecationWarning
- EOFError
- Ellipsis
- EncodingWarning
- EnvironmentError
- Exception
- ExceptionGroup
- False
- FileExistsError
- FileNotFoundError
- FloatingPointError
- FutureWarning
- GeneratorExit
- IOError
- ImportError
- ImportWarning
- IndentationError
- IndexError
- InterruptedError
- IsADirectoryError
- KeyError
- KeyboardInterrupt
- LookupError
- MemoryError
- ModuleNotFoundError
- NameError
- None
- NotADirectoryError
- NotImplemented
- NotImplementedError
- OSError
- OverflowError
- PendingDeprecationWarning
- PermissionError
- ProcessLookupError
- RecursionError
- ReferenceError
- ResourceWarning
- RuntimeError
- RuntimeWarning
- StopAsyncIteration
- StopIteration
- SyntaxError
- SyntaxWarning
- SystemError
- SystemExit
- TabError
- TimeoutError
- True
- TypeError
- UnboundLocalError
- UnicodeDecodeError
- UnicodeEncodeError
- UnicodeError
- UnicodeTranslateError
- UnicodeWarning
- UserWarning
- ValueError
- Warning
- ZeroDivisionError
- build_class
- debug
- doc
- import
- loader
- name
- package
- spec
- abs
- aiter
- all
- anext
- any
- ascii
- bin
- bool
- breakpoint
- bytearray
- bytes
- callable
- chr
- classmethod
- compile
- complex
- copyright
- credits
- delattr
- dict
- dir
- divmod
- enumerate
- eval
- exec
- exit
- filter
- float
- format
- frozenset
- getattr
- globals
- hasattr
- hash
- help
- hex
- id
- input
- int
- isinstance
- issubclass
- iter
- len
- license
- list
- locals
- map
- max
- memoryview
- min
- next
- object
- oct
- open
- ord
- pow
- property
- quit
- range
- repr
- reversed
- round
- set
- setattr
- slice
- sorted
- staticmethod
- str
- sum
- super
- tuple
- type
- vars
- zip
If you want to handle each error individually, then you can specify the error name, as listed above, after the 'except' word. An example follows:
Code:
try:
file1 = open("/home/jarret/test.txt")
except FileNotFoundError:
file1 = open("/home/jarret/test.txt","w")
file1.close()
file1 = open("/home/jarret/test.txt","r")
except NotADirectoryError:
print ("You specified an invalid folder!")
If the file was not found, we created it. If we by chance specified an incorrect folder name, then we are told so.
If an error is elusive to find the proper name, you can use the code:
Code:
except Exception as e:
print(f"{type(e).__name__}")
exit()
The code will print out the same code as listed in the list above for you to use in your code for an exception.
Conclusion
Look at the same code I gave. Try to cause a few errors of your own and trap the error and resolve it, like I did with the 'FileNotFoundError'.
Keep in mind about any code that may cause issues and trap the error so you can resolve it.