Java中throw与throws用法有何不同之处?

2026-05-26 10:592阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计386个文字,预计阅读时间需要2分钟。

Java中throw与throws用法有何不同之处?

代码实例:+ 问题:为什么testRunntimeException()方法没有出现编译错误,而testCheckedException()方法却出现未处理的异常 + 分析:Exception分为两类:checked exception、runtime exception;直接继承自Exception的为checked exception,而直接继承自Throwable的为runtime exception。

代码实例:javapublic class ExceptionExample { public static void main(String[] args) { testRunntimeException(); testCheckedException(); }

public static void testRunntimeException() { int a=10 / 0; // 运行时异常,不会导致编译错误 }

public static void testCheckedException() { try { throw new IOException(IO error); // 检查异常,需要try-catch处理 } catch (IOException e) { e.printStackTrace(); } }}

代码实例:

Java中throw与throws用法有何不同之处?

问题:为什么testRunntimeException()方法没有出现编译错误提示,而testCheckedException()方法却出现unhandle exception?

分析:

  Excepiton分两类:checked exception、runtime exception;直接继承自Exception就是checked exception,继承自RuntimeException就是runtime的exception。

  你可以简单地理解checked exception就是要强制你去处理这个异常(不管你throws多少层,你终归要在某个地方catch它);而runtime exception则没有这个限制,你可以自由选择是否catch。

  那些强制异常处理的代码块,必须进行异常处理,否则编译器会提示“Unhandled exception type Exception”错误警告。

这里testRunntimeException()方法是runtime exception异常,testCheckedException()方法是exception异常,属于checked exception异常

所以testCheckedException()方法却出现unhandle exception

怎么解决testCheckedException()方法却出现unhandle exception?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计386个文字,预计阅读时间需要2分钟。

Java中throw与throws用法有何不同之处?

代码实例:+ 问题:为什么testRunntimeException()方法没有出现编译错误,而testCheckedException()方法却出现未处理的异常 + 分析:Exception分为两类:checked exception、runtime exception;直接继承自Exception的为checked exception,而直接继承自Throwable的为runtime exception。

代码实例:javapublic class ExceptionExample { public static void main(String[] args) { testRunntimeException(); testCheckedException(); }

public static void testRunntimeException() { int a=10 / 0; // 运行时异常,不会导致编译错误 }

public static void testCheckedException() { try { throw new IOException(IO error); // 检查异常,需要try-catch处理 } catch (IOException e) { e.printStackTrace(); } }}

代码实例:

Java中throw与throws用法有何不同之处?

问题:为什么testRunntimeException()方法没有出现编译错误提示,而testCheckedException()方法却出现unhandle exception?

分析:

  Excepiton分两类:checked exception、runtime exception;直接继承自Exception就是checked exception,继承自RuntimeException就是runtime的exception。

  你可以简单地理解checked exception就是要强制你去处理这个异常(不管你throws多少层,你终归要在某个地方catch它);而runtime exception则没有这个限制,你可以自由选择是否catch。

  那些强制异常处理的代码块,必须进行异常处理,否则编译器会提示“Unhandled exception type Exception”错误警告。

这里testRunntimeException()方法是runtime exception异常,testCheckedException()方法是exception异常,属于checked exception异常

所以testCheckedException()方法却出现unhandle exception

怎么解决testCheckedException()方法却出现unhandle exception?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。