I have a list with 2 elements a=[1,2]
if I put for example a[2] then it will mark
> > Traceback (most recent call last): File "<pyshell#13>", line 1, in <module>
> if a[2]== IndexError(): IndexError: list index out of range
If I put a if
to 'fix it' that says for example:
if a[2]== IndexError:
print('Fuera de Rango')
Logical It won't work.
I know there are several ways to solve this problem such as:
if a[2]==len(a):
print('Fuera de Rango')
But the main question is whether the error can be avoided directly as in the first example without the need to put a condition like the length or something like that, but using a function that avoids these errors.
Thank you! and I hope I made myself understood.
If you want to prevent the program from terminating with an exception because of trying to index with an index out of range, none of the options you show will work, at the time you try to evaluate
a[2]
you will have theIndexError
.With a conditional that checks the length of the list and checks if the index is valid, something like this should be done:
However you can use a block
try-except
to catch the exception and handle it as you see fit:Basically the interpreter tries to carry out what is inside the
try
, in case of failure due to aIndexError
it carries out what is inside theexcept
. You can catch any exception ifexcept
it isn't explicitly followed by an error, although as you can imagine it can be a big cause of errors that are passed silently:You can handle different errors differently by using multiple statements
except
:Or capture multiple types in the same block using a tuple:
You can use a function that returns the element of the list if it exists, or a value that you want otherwise, without throwing an exception using the same idea (something similar to what the method does
dict.get
for example).More "fancy" options exist by creating our own wrapper class or inheriting (not recommended for reasons besides the point) / composing from
list
. However, if a container that implements the functionality oflist
but is required, a good option is to inherit fromcollections.UserList
:The class
MyList
implements all the functionalities of a list but if we index with an incorrect index it returns usNone
, it does not throw an exception.Errors that occur at run time (that is, when a particular statement is being executed) trigger what is called an exception .
Exceptions can be caught from the code itself and a decision made in the code as to what to do. Only when they are not captured do they end up being visible to the user, showing a Traceback like the one you put in your question. In this Traceback , it is reported what exception occurred, and in what line of code, as well as what functions were in execution at that moment (that is, from what function the one that caused the exception had been called, and from which one had it been called). called in turn to the previous one, etc.)
In the documentation you have all the details on how to handle exceptions , or how to throw your own.
A brief summary would be the following.
handle exceptions
When you are going to execute a block of code that might fail with an exception, put that block of code inside a clause
try:
. Following that clause put another callexcept X:
, beingX
the name of an exception. Inside this second block, you write code that will be executed in case the exception occursX
. The blockexcept X
can be repeated several times with different cases ofX
, to handle each exception differently.So:
Note that when an exception occurs, in addition to (or instead of) printing what error occurred, you must take some corrective action. In the previous example I have assumed that we wanted to access a data, and that if we go out of range, the data is equal to zero. This may or may not make sense in your application. It depends on what you are going to do with that data later. Another option could be to make the
dato
equal toNone
. Yet another option could be to abort the execution of the program withquit()
to prevent it from executing anything else (which is what python does when it encounters an exception not handled by code).Throw your own exception
You may also be writing a function that is going to be called from another site, and you want to detect possible errors and inform the caller that one of those errors has occurred. When you want to do that, you can put
raise X()
, beingX
the name of the exception you want to raise. It can be one of those that python has already defined, or others that you have created (they would be classes that directly or indirectly inherit from the classException
).For example your code could contain something like:
Whoever calls that function passing an
n
incorrect would run into the exceptionIndexError
that has been thrown from your code when entering theif
. If you haven't handled that exception usingtry/catch
, the exception will go up to the next function that would have called the one that called yours. If at the end the main program is reached without anyone having handled the exception, the program will break and the user will be shown the message that we put when throwing the exception.More details in the aforementioned documentation.