No exception of type Exception can be thrown, an exception type must be a subclass of Throwable

VL4DiMiRG picture VL4DiMiRG · Oct 26, 2018 · Viewed 17k times · Source

I was seaching this problem in other questions but still didn't figure out what does exactly mean Throwable. Read a few articles about it (its superclas bla bla bla) but still don't know how to implement it. Forgot to mention i am new to java. Any advice would be gratefully accepted :D

Here is the Exception class:

class Exception {
private int pDen;
private int pMes;
private int kDen;
private int kMes;

public Exception(int pDen, int pMes, int kDen, int kMes) {
    super();
    this.pDen = pDen;
    this.pMes = pMes;
    this.kDen = kDen;
    this.kMes = kMes;
}
public void message()
{
    System.out.println("Isklucok");
}
public void promena()
{
    int tmpDen = 0;
    int tmpMes = 0;
    tmpDen = pDen;
    pDen = kDen;
    kDen = tmpDen;
    tmpMes = pMes;
    pMes = kMes;
    kMes = tmpMes;
}

}

And here is the code that i run in other class where shoud i catch my exception where is thrown.

try {
        if(pMes > kMes)
        {
            throw new Exception(pDen,pMes,kDen,kMes);
        }
        else if(pMes == kMes)
            if(pDen > kDen)
            {
                throw new Exception(pDen,pMes,kDen,kMes);
            }
    }
    catch(Exception e)
    {
        e.message();
        e.promena();
    }

Answer

user10367961 picture user10367961 · Oct 26, 2018

Make your custom exception extends something from the Throwable hierarchy.

For example

// Exception here is java.lang.Exception, not the class from your example
public class MyException extends Exception {

    // ...

}