zoukankan      html  css  js  c++  java
  • Java-- 异常(2)

      晚上打雷了,鉴于前天打雷吧路由器和猫都弄坏了,今天就不写解释了。直接上代码。

    主要是自定义异常的使用,通过System.err而将错误发送给标准错误流。通常这比把错误的信息输出到System.out要好,因为System.out也许会被重定向。

    如果把结果送到System.err,它就不会随System.out一起被重定向,这样更容易被用户注意。

    也可以以为异常类定义一个接受字符串参数的构造器。

     1 package com.exceptions;
     2 
     3 
     4 class MyException extends Exception{
     5     public MyException(){
     6     }
     7     public MyException(String msg){ super(msg);}
     8 }
     9 
    10 public class FullConstructors {
    11     public static void f() throws MyException{
    12         System.out.println("Throwing MyException from f()");
    13         throw new MyException();
    14     }
    15     
    16     public static void g() throws MyException{
    17         System.out.println("Throwing MyException fron g()");
    18         throw new MyException("Originated in g()");
    19     }
    20     
    21     public static void main(String[] args){
    22         try{
    23             f();
    24         }catch(MyException e){
    25             e.printStackTrace(System.out);
    26         }
    27         try{
    28             g();
    29         }catch(MyException e)
    30         {
    31             e.printStackTrace(System.out);
    32         }
    33     }
    34 }

    结果:

    1 Throwing MyException from f()
    2 com.exceptions.MyException
    3     at com.exceptions.FullConstructors.f(FullConstructors.java:13)
    4     at com.exceptions.FullConstructors.main(FullConstructors.java:23)
    5 Throwing MyException fron g()
    6 com.exceptions.MyException: Originated in g()
    7     at com.exceptions.FullConstructors.g(FullConstructors.java:18)
    8     at com.exceptions.FullConstructors.main(FullConstructors.java:28)
  • 相关阅读:
    jquery easy ui 简单字段选择搜索实现
    (转)EasyUI 分页总结
    EasyUI 搜索框
    微信公众号开发简单介绍
    【POJ3740】Easy Finding DLX(Dancing Links)精确覆盖问题
    推断View是否显示在界面上
    菜鸟调错(八)—— Maven编译错误:不兼容的类型的解决方式
    js对table操作(添加删除交换上下TR)
    NBUT 1222 English Game(trie树+DP)
    Android 返回键的处理
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3801485.html
Copyright © 2011-2022 走看看