I am entering the world of Python and I have a question that has arisen, I have been looking around but I have not found anything that convinces me and I hope that here the hard one will be clarified.
The question is on the topic of exceptions in Python and how to throw and catch them afterwards.
I put an example in Java and I want to know how it could be done in Python:
public void setEdad(int edad) {
if (edad <= 0)
throw new Exception("La edad debe ser positiva.");
this.edad = edad;
}
And then before assigning a value I capture it:
try {
Persona persona = new Persona();
persona.setEdad(-10);
} catch (Exception e) {
System.out.println(e.getMessage());
}
This is a test example to show what I want to achieve.
How could I do that in Python and be able to throw exceptions like in java?
Greetings and thank you.
For this type of exceptions due to passing an invalid argument to a method/function,
ValueError
or a subclass of it is usually used. The simplest is:I usually prefer to create a custom class for this, which gives you a lot more freedom and clarity to the code:
In
except
it you can catch all exceptions and not just the custom one usingException
:You have already been given correct answers to your question. Although the question was about how to throw exceptions and how to intercept them, for cases like your example it would be better to use "asserts" :
If the condition is not met, an exception is raised
AssertionError
that could be intercepted. But trapping exceptions only makes sense if you want to fix the error and get the program to continue. If that's the case, it's best to do the fix and avoid throwing exceptions.The advantage of using asserts is that they "disappear" when the code is optimized (parameter
-O
). You can safely use them to secure testing in development without fear of slowing down the final optimized version when you deploy it to production.You can throw an Exception using
raise
, I also told you in case you didn't know, that in python the "getters" or "setters" methods of Java are not necessary, obviously yes, if you need to do a validation on a value, but anyway it is still a convention and there is no language restriction in this regard, you could always be doing itobjeto.edad = -1
and it would be totally valid. To get closer to the mechanics of Java, it is convenient to use the decorators@Property
and@Prop.setter