如何抛出IOException?
public class ThrowException { public static void main(String[] args) { try { foo(); } catch(Exception e) { if (e instanceof IOException) { System.out.println("Completed!"); } } } static void foo() { // what should I write here to get an exception? } }
嗨! 我刚刚开始学习例外,需要赶上一个考试,所以请有人能为我提供解决方案吗? 我会非常感激的。 谢谢!
static void foo() throws IOException { throw new IOException("your message"); }
try { throw new IOException(); } catch(IOException e) { System.out.println("Completed!"); }
throw new IOException("Test");
我刚刚开始学习exception并需要捕获exception
抛出exception
throw new IOException("Something happened")
要捕获此exception最好不要使用Exception
因为它是非常通用的,而是捕获您知道如何处理的特定exception:
try { //code that can generate exception... }catch( IOException io ) { // I know how to handle this... }
如果目标是从foo()
方法抛出exception,则需要按如下方式声明它:
public void foo() throws IOException{ \\do stuff throw new IOException("message"); }
然后在你的主要:
public static void main(String[] args){ try{ foo(); } catch (IOException e){ System.out.println("Completed!"); } }
请注意,除非声明foo抛出IOException,否则尝试捕获一个将导致编译器错误。 使用catch (Exception e)
和instanceof
对其进行编码将防止编译器错误,但这是不必要的。
请尝试以下代码:
throw new IOException("Message");
也许这有助于……
请注意以下示例中捕获exception的更简洁方法 – 您不需要e instanceof IOException
。
public static void foo() throws IOException { // some code here, when something goes wrong, you might do: throw new IOException("error message"); } public static void main(String[] args) { try { foo(); } catch (IOException e) { System.out.println(e.getMessage()); } }