可能的重复: 我怎样才能自己写一个异常?
我想在Java中创建一个自定义的异常,怎么做?
...
try{
...
String word=reader.readLine();
if(word.contains(" "))
/*create custom exception*/
}
catch(){
当我用throw new...
创建我的自定义异常时,我得到的错误是unreported exception...must be caught or declared to be thrown
。
你应该能够创建一个自定义的异常类,例如,扩展了Exception
类。
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
使用方法:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}