Reputation: 84
I am trying to create my own exception, which extends the Exception class, but when I try to throw it, the compiler throws a compile-time error.
Here is my exception class:
package Exception;
public class notAdultException extends Exception {
@Override
public String toString() {
return ("you are not adult");
}
}
Here is where I try to throw the exception:
int Age = 16;
try {
if (Age < 18) {
throw new notAdultException();
}
catch (notAdultException t) {
System.out.println(t);
}
And here is the error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
No exception of type notAdultException can be thrown; an exception type must be a sublass of Throwable
No exception of type notAdultException can be thrown; an exception type must be a sublass of Throwable
at Exception.Exception.main(Exception.java:44)
Upvotes: 0
Views: 686
Reputation: 89374
The issue is that you have a class named Exception
in the same package, so you will need to qualify access to java.lang.Exception
. Demo
public class notAdultException extends java.lang.Exception {
@Override
public String toString(){
return "you are not adult";
}
}
As a side note, you should always follow the Java naming conventions e.g. the name of your class should be NotAdultException
instead of notAdultException
and the name of your package should be something like my.exceptions
.
Upvotes: 1
Reputation: 785
Try this:
public class notAdultException extends Exception {
public notAdultException(String message) {
super(message);
}
}
Don't forget to import java.lang.Exception (or use the full qualifier as mentioned above.)
Upvotes: 1