0

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 ?

pheromix
  • 18,213
  • 29
  • 88
  • 158
  • 2
    Just read about checked vs. unchecked exceptions: http://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation – home Nov 02 '16 at 06:55
  • 2
    you got to declare in your method that you may throw an exception from it. – Sikorski Nov 02 '16 at 06:55

2 Answers2

3

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.RuntimeException 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

ben75
  • 29,217
  • 10
  • 88
  • 134
Vasu
  • 21,832
  • 11
  • 51
  • 67
-1

Your del method should throw PkDeleteException. Your method should be like follow

public void del(@RequestParam String id) throws PkDeleteException  {

    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);

    }

}
ben75
  • 29,217
  • 10
  • 88
  • 134
janith1024
  • 1,042
  • 3
  • 12
  • 25