Reputation: 39
I am trying to get the PSQLException exception, however it tells me that this block cannot be reached, does anyone know why? I mean, I can't run or anything, Eclipse marks it as an error. However, if, for example, I put Exception e, instead of PSQLException e, it does not give an error.
@DeleteMapping("/delete/{pais_id}")
public Resultado<Pais> eliminaPais(@PathVariable("pais_id") Long pais_id, HttpServletResponse response) {
Resultado<Pais> res = new Resultado<>();
try {
Optional<Pais> existePais = paisService.getFindById(pais_id);
if (existePais.isPresent()) {
if (pais_id != null) {
// monedaService.setANullPais(pais_id);
try{
paisService.getEliminaPais(pais_id);
res.setCodigo(200);
res.setMensaje("El país " + existePais.get().getNombre() + " ha sido eliminado");
res.setDatos(existePais.get());
}catch(PSQLException e) { //HERE
res.setCodigo(400);
res.setMensaje("El país no " + existePais.get().getNombre() + " ha sido eliminado");
res.setDatos(null);
}
}
} else {
res.setSuccess(false);
res.setMensaje("Se ha producido un error, el ID proporcionado no existe " + pais_id);
res.setCodigo(400);
}
} catch (Exception e) {
res.setSuccess(false);
res.setMensaje("Se ha producido un error: " + e.getMessage());
res.setCodigo(400);
}
response.setStatus(res.getCodigo());
return res;
}
Upvotes: 0
Views: 1123
Reputation: 44150
PSQLException
is a checked exception. That means methods which throw that exception are required to document it in their signature. The compiler has detected that no code in your try block throws that type of exception. It knows that the catch block is redundant and is likely a user error, so it produces a failure so you can fix it.
Exception
is a broader classification and includes the set of all unchecked exceptions, which are not required to be documented in a method signature. In this case, the compiler doesn't know exactly what might be thrown, but it knows that something might be. So in this case, the catch block is not (necessarily) redundant, and so it will not report the same failure.
Upvotes: 2
Reputation: 79
Since it is an checked exception, you are trying to catch an exception which is never thrown.
You try block code should throw an Checked exception then only you can catch it.
In your case that is PSQLException.
Upvotes: 0