zoukankan      html  css  js  c++  java
  • Java异常处理-throws和throw关键字

    throws表示当前方法不处理异常,而是交给方法的调用出去处理;

    throw表示直接抛出一个异常;

     
    public class Demo1 {
     
        /**
         * 把异常向外面抛
         * @throws NumberFormatException
         */
        public static void testThrows()throws NumberFormatException{
            String str="123a";
            int a=Integer.parseInt(str);
            System.out.println(a);
        }
         
        public static void main(String[] args) {
            try{
                testThrows();  
                System.out.println("here");
            }catch(Exception e){
                System.out.println("我们在这里处理异常");
                e.printStackTrace();
            }
            System.out.println("I'm here");
        }
    }

    这里我们直接把异常抛出了。

    运行输出:

    我们在这里处理异常
    java.lang.NumberFormatException: For input string: "123a"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:580)
        at java.lang.Integer.parseInt(Integer.java:615)
        at com.java1234.chap04.sec03.Demo1.testThrows(Demo1.java:11)
        at com.java1234.chap04.sec03.Demo1.main(Demo1.java:17)
    I'm here

    throw表示直接抛出一个异常;

    我们可以根据业务在代码任何地方抛出异常:

    package com.java1234.chap04.sec03;
     
    public class Demo2 {
     
        public static void testThrow(int a) throws Exception{
            if(a==1){
                // 直接抛出一个异常类
                throw new Exception("有异常");
            }
            System.out.println(a);
        }
         
        public static void main(String[] args) {
            try {
                testThrow(1);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    运行输出:

    java.lang.Exception: 有异常
        at com.java1234.chap04.sec03.Demo2.testThrow(Demo2.java:8)
        at com.java1234.chap04.sec03.Demo2.main(Demo2.java:15)
  • 相关阅读:
    源码安装extundelete以及对遇到问题的解决
    centos 连不上网
    memcache 永久数据被踢
    svn 分支
    HTML5 中已经可以用 Ajax 上传文件了,而且代码非常简单,借助 FormData 类即可发送文件数据。
    sublime安装DocBlockr注释插件
    rsync 无密码 传输
    滚动条滑到底部,加载更多
    svn 同步脚本
    蒲公英[分块]
  • 原文地址:https://www.cnblogs.com/xyg-zyx/p/9833410.html
Copyright © 2011-2022 走看看