pheromix pheromix - 1 month ago 11
Java Question

Throwing an exception makes error of unhandled exception

I created an exception :

public class PkDeleteException extends java.lang.Exception {

private static final long serialVersionUID = 1L;

public PkDeleteException(String msg) {

super(msg);

}

}


Now I threw it in the catch block of some code :

import com.ambre.pta.utils.PkDeleteException;

public class AdminRole {

@Autowired
private Environment env;

@Autowired
private RoleDAO roleDao;

public void del(@RequestParam String id) {

try {

roleDao.delete(id);

} catch (org.hibernate.exception.ConstraintViolationException e) {

Role role = roleDao.get(id);

String errMsg = env.getProperty("admin.list.profils.err.suppr");

errMsg = errMsg.replace("%s", role.getRole_lib());

throw new PkDeleteException(errMsg);

}

}

}


But I got an error
Unhandled exception type PkDeleteException
!

There are suggested solutions proposed by Eclipse but I do not want to follow them ! So why is there this error ?

Answer

In general or for most of the scenarios, you never create a custom exception by extending java.lang.Exception class directly, rather you need to extend java.lang.Runtime class (or it's subtypes, which is even more preferable).

As your current PkDeleteException is checked Exception, you need to declare that in your method signature using throws clause (option-2, not preferable) or the best practice is to convert it into unchecked Exception (option-1) like below:

Option(1) - Use unchecked Exception (Preferable):

public class PkDeleteException extends RuntimeExcetion {

    private static final long serialVersionUID = 1L;

    public PkDeleteException(String msg) {

        super(msg);

    }

}

Option(2): Change your method signature

from

public void del(@RequestParam String id)

to

public void del(@RequestParam String id) throws PkDeleteException

I suggest you to have a look at here