我想在 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
throw new...
unreported exception...must be caught or declared to be thrown
您应该能够创建一个扩展该类的自定义异常类 Exception ,例如:
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 }