zoukankan      html  css  js  c++  java
  • Java异常处理之throw和声明throws·12

    • 代码出异常常见的处理方法
      • try catch捕获
      • throws 声明异常 往外抛出
        • 语法:throws字句放在方法参数列表的右括号之后,一个方法可以声明抛出多个异常,多个异常之间用逗号隔开。
        • 例子

    public class Main{
        public static void readChar() throws IOException,RemoteException{
            int input =System.in.read();
        }
    }
    • try catch中捕获了异常,处理方法
      • 当前捕获自己处理
      • 捕获自己处理然后继续往外面抛异常
        • 语法
    throw new ExceptionName("异常信息......");
        • 例子
    throw new IOException("File not found.....");
    • 总结
      • 当抛出一个被检查的异常,我们必须用try-catch块去处理它,或者在方法声明中使用throws子句继续往外抛
      • 如果在方法中后面加了throws声明抛出多个异常,那么在可能出现异常的代码块中也要加throw new对面的exception、最后在调用该方法时也要加上try/catch处理;
      • 处理异常两种方法:
        • 当地捕获自己处理

    try{
        //可能出现异常的代码块
    }catch(ExceptionName e){
        // 出现异常后的处理方法
    }
      • 继续往外面抛异常

    public class TestException5 {
        // 第一种,当前不处理,继续往外面抛异常
        public static void main(String[] args) throws Exception{
                divide(2,0);
    }
    • 总代码块
    • package chapter7_5;
      
      /**
       * @ClassName: TestException5
       * @Author: mr.chen
       * @Date:2021/2/16
       * @Version: 1.0
       **/
      public class TestException5 {
          // 第一种,当前不处理,继续往外面抛异常
          public static void main(String[] args) throws Exception{
              // 第二种,当地处理异常
      //        try {
      //            int result = divide(2, 0);
      //            System.out.println("result :" + result);
      //        } catch (Exception e) {
      //            System.out.println("出main异常了哟......");
      //        }
              divide(2,0);
          }
      
          public static int divide(int num1, int num2) throws Exception {
              try {
                  return num1 / num2;
      
              } catch (Exception e) {
                  System.out.println("出异常了.......");
                  throw new Exception("异常了呀.......");
              }
      //        return -1;
          }
      
      }
      

        

    Bug? 不存在的!
  • 相关阅读:
    VS项目如何运用svn的忽略列表
    Hyper-V如何应用新的网卡
    android:Layout_weight的深刻理解
    使用WebView出现web page not available
    如何在android模拟器中导入搜狗输入法?
    ASP.Net生成静态HTML页
    微软URLRewriter.dll的url重写的简单使用(实现伪静态)
    servlet中获得tomcat项目根目录的绝对路径
    Log4j使用指南
    处理URL传递中文乱码问题
  • 原文地址:https://www.cnblogs.com/mrchenyushen/p/15028227.html
Copyright © 2011-2022 走看看