Java异常怎么自定义

其他教程   发布日期:2023年08月26日   浏览次数:437

这篇文章主要介绍“Java异常怎么自定义”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java异常怎么自定义”文章能帮助大家解决问题。

异常方法

  1. //返回此可抛出对象的详细信息消息字符串
  2. public String getMessage()
  3. //将此可抛发对象及其回溯到标准错误流。此方法在错误输出流上打印此 Throwable 对象的堆栈跟踪
  4. //最为详细
  5. public void printStackTrace()
  6. //返回此可抛件的简短说明
  7. public String toString()

对于1/0这个异常

  1. try{
  2. int i = 1/0;
  3. } catch(Exception e){
  4. System.out.println("e = " + e);
  5. System.out.println("-----------------");
  6. System.out.println("e.getMessage() = " + e.getMessage());
  7. System.out.println("-----------------");
  8. System.out.println("e.getStackTrace() = " + Arrays.toString(e.getStackTrace()));
  9. System.out.println("-----------------");
  10. System.out.println("e.getLocalizedMessage() = " + e.getLocalizedMessage());
  11. System.out.println("-----------------");
  12. System.out.println("e.getCause() = " + e.getCause());
  13. System.out.println("-----------------");
  14. System.out.println("e.getClass() = " + e.getClass());
  15. System.out.println("-----------------");
  16. System.out.println("e.getSuppressed() = " + Arrays.toString(e.getSuppressed()));
  17. }
  1. e = java.lang.ArithmeticException: / by zero
  2. -----------------
  3. e.getMessage() = / by zero
  4. -----------------
  5. e.getStackTrace() = [省略27行,com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)]
  6. -----------------
  7. //可能的原因
  8. e.getCause() = null
  9. -----------------
  10. //一个数组,其中包含为传递此异常而禁止显示的所有异常。
  11. //就是用try捕获却不做事的
  12. e.getSuppressed() = []

自定义异常

作用

让控制台的报错信息更加的见名知意

定义

1.定义异常类,写继承关系。
名字要见名知义,继承于异常类。
像运行时可以继承RuntimeException
在开发过程中一般会有多种异常类,小的会继承自定义的大的。

2.写构造方法
需要书写空参和带参的构造。
可以调用父类的也可以自定义

增强try(try-with-resources)

作用

简化释放资源的步骤

条件

自动释放的类需要实现autocloseable的接口
这样在特定情况下会自动释放,还有的就是stream流中提到过。

jdk7

  1. try(创建对象资源1;创建对象资源2){
  2. }catch(){
  3. }

例如这样的代码可以改写成

  1. BufferedInputStream b = null;
  2. try {
  3. b = new BufferedInputStream(new FileInputStream(""));
  4. }catch (Exception e) {
  5. e.printStackTrace();
  6. }finally {
  7. if (b!=null) {
  8. try {
  9. b.close();
  10. } catch (IOException e) {
  11. throw new RuntimeException(e);
  12. }
  13. }
  14. }
  1. try (BufferedInputStream b = new BufferedInputStream(new FileInputStream(""));){
  2. }catch (Exception e) {
  3. e.printStackTrace();
  4. }

jdk9

  1. 创建对象1
  2. 创建对象2
  3. try(变量名1;变量名2){
  4. }catch(){
  5. }

上面的代码可以改写成,
不过需要注意的是创建对象也需要异常处理,我们这里选择抛出

  1. public void testTryWithResource() throws FileNotFoundException {
  2. BufferedInputStream b = new BufferedInputStream(new FileInputStream(""));
  3. try (b) {
  4. } catch (Exception e) {
  5. e.printStackTrace();
  6. }
  7. }

以上就是Java异常怎么自定义的详细内容,更多关于Java异常怎么自定义的资料请关注九品源码其它相关文章!