Mogelijk duplicaat: Hoe kan ik zelf een Exception schrijven?
Ik wil graag een eigen exception maken in Java, hoe doe ik dat?
...
try{
...
String word=reader.readLine();
if(word.contains(" "))
/*create custom exception*/
}
catch(){
Als ik mijn eigen uitzondering maak met throw new...
, krijg ik de foutmelding unreported exception...must be caught or declared to be thrown
U zou in staat moeten zijn om een aangepaste uitzonderingsklasse te maken die de Exception
klasse uitbreidt, bijvoorbeeld:
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
Usage:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}
Een exceptie is een klasse zoals elke andere klasse, behalve dat het een uitbreiding is van Exception
. Dus als je je eigen klasse maakt
public class MyCustomException extends Exception
kun je zo'n instantie gooien met
throw new MyCustomException( ... );
//using whatever constructor params you decide to use
En dit is misschien interessant om te lezen