Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to cause an ValueError in Python

I have this code:

chars = #some list

try:
    indx = chars.index(chars)
except ValueError:
    #doSomething
else:
   #doSomethingElse

I want to be able to do this because I don't like knowfully causing Exceptions:

chars = #some list

indx = chars.index(chars)

if indx == -1:
    #doSomething
else:
   #doSomethingElse

Is there a way I can do this?

like image 625
jjnguy Avatar asked Sep 25 '08 04:09

jjnguy


People also ask

What causes a ValueError in Python?

What Causes ValueError. The Python ValueError is raised when the wrong value is assigned to an object. This can happen if the value is invalid for a given operation, or if the value does not exist. For example, if a negative integer is passed to a square root operation, a ValueError is raised.

How do you avoid ValueError?

Use a try/except statement to ignore the ValueError when removing an element from a list. If an error occurs, it gets handled by the except block where you can use the pass statement to ignore it.

When should you raise ValueError?

Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value. Also, the situation should not be described by a more precise exception such as IndexError.

What are the 3 errors in Python?

In python there are three types of errors; syntax errors, logic errors and exceptions.


2 Answers

Note that the latter approach is going against the generally accepted "pythonic" philosophy of EAFP, or "It is Easier to Ask for Forgiveness than Permission.", while the former follows it.

like image 60
Kevin Little Avatar answered Oct 03 '22 06:10

Kevin Little


if element in mylist:
    index = mylist.index(element)
    # ... do something
else:
    # ... do something else
like image 36
Jerub Avatar answered Oct 03 '22 05:10

Jerub