5
Java, brings with it several ready-made Exceptions, Illegalargumentexception, Illegalstateexception, Runtimeexception, among others.
Creating a Custom Java Exception?
I have the following method - sumAndPrint(int,int)
Sum two integers and print them to the Output associated with the System.
public void sumAndPrint(int x, int y) throws Exception{
if(x < 0 || y < 0){
//trocar uma excessao específica - NumeroNegativoException
throw new Exception("Numeros negativos nao permitidos");
}
System.out.println("soma -> " + (x+y));
}
However, I do not accept as arguments values less than zero.
I want to create my own exception(checked Exception) - NumeroNegativoException
- how do I do that?
The purpose of this question/answer is to share knowledge about how to create exceptions in Java.
Do not create exceptions just because you want a more specific name. In the case of your example use
IllegalArgumentException
because that’s what it’s all about.– ramaral
This issue has the purpose of sharing knowledge of how to create . This is just an @ramaral example
– Filipe Miranda
Tip: "Exception" is spelled "ç", not "ss".
– Victor Stafusa