Cómo evitar excepciones (pruebe catch block) como control de flujo
Frecuentes
Visto 276 equipos
1
In the following method how can i aovid using try catch block but still call the correct method on id to get User/group? (Best Practices) Thanks in advance
public Principal getPrincipal(String id) {
Principal principal;
try {
principal = getUserById(id);
return principal;
} catch (Exception exception) {
// nothing to do, maybe id is for group
}
principal = getGroup(id);
return principal;
}
getUSerById(), throws a exception called EntityNotException,
3 Respuestas
0
hacer función getUserById
such way that if there is no user found it return null
public Principal getPrincipal(String id) {
Principal principal = getUserById(id);
if (principal == null) {
principal = getGroup(id);
}
return principal;
}
Respondido el 12 de junio de 14 a las 10:06
0
There's no way to avoid try/catch block if you cannot modify getUserById(String)
method. That's fine to have such check, but be very careful when you just ignore an exception.
Also you can just extract a small obtener el método Me gusta esto:
public Principal getUserByIdIngorinException(String id) {
try {
return getUserById(id);
} catch (Exception ignored) {
// ignore the exception
}
return null;
}
Respondido el 12 de junio de 14 a las 10:06
0
In that case I'd consider having your getUserById(String id)
volvemos null
, en lugar de un EntityNotException
if no user can be found - Exceptions are to be used for Servicio circumstances, such as a failure beyond your control (Network connections vanished, no more memory is available, etc.). Your code could look something like the following:
public Principal getPrincipal(String id) {
Principal principal = getUserById(id);
if (principal == null) {
//Try by group ID instead
principal = getGroup(id);
}
return principal;
}
Make sure you're certain of the return types of your methods - from their names it doesn't sound like getUserById(String id)
e getGroup(String id)
definitely return a Principal
object - the first sounds like it could return any type of User
and the second a Group
, sea lo que sea.
Alternatively, given the caller of this method presumably knows whether they have a userId
o un groupId
, have you considered separate methods getPrincipalByUserId(String userId)
e getPrincipalByGroupId(String groupId)
?
Respondido el 12 de junio de 14 a las 16:06
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java exception try-catch or haz tu propia pregunta.
As a best practice you should handle Checked Exceptions and your program should ideally not generate Unchecked Exceptions. - AurA
puedes añadir
throws Exception
after method, likepublic Principal getPrincipal(String id) throws Exception{
en lugar detry..catch
. - user3145373 ツAs a general point, I'd be a bit more specific about the type of
Exception
that you catch. If you're only interested in theEntityNotException
, only catch that exception. - Edd