zoukankan      html  css  js  c++  java
  • 异常throws关键字 异常throw关键字

    throws关键字

    class Math{
        public int div(int i,int j)throws Exception{   //throws Exception声明的方法不对此类异常进行处理,而由该方法的调用者负责处理
            int temp=i/j;
            return temp;
        }
    }
    public class seven4{
        public static void main(String[] args){
            Math m=new Math();
            try{
                System.out.println("除法操作:"+m.div(10,2)); 
            }
            catch(Exception e){
                e.printStackTrace();    //打印异常
            }
        }
    }

    throw关键字

    java中还可以直接使用throw关键字人为抛出一个异常,人工抛出异常的格式:

      throw 异常类对象;    ---被抛出的必须是Throwable或其子类对象

         IOException e=new IOException();

         throw e;      

       程序执行throw语句后立即终止,然后在包含它的所有try块中从里向外寻找含有与其类型匹配的catch子句。

    public class ThrowDemo1{
        public static void main(String args[]){
            try{
                throw new Exception("自己抛着玩的。") ;    //抛出时直接抛出异常实例化对象即可
    
            }catch(Exception e){
                System.out.println(e) ;
            }
        }
    }

    自定义异常类

    虽然Java的内置异常处理能够处理大多数常见错误,但用户仍需建立自己的异常类型来处理特殊情况。这时可以通过创建Exception的子类来定义自己的异常类。

    格式:class 类名 extends Exception{

         … …

         }

    class MyException extends Exception{
        MyException(String str){  //在定义异常类时一般需要定义构造方法接收异常信息,该信息可由父类的构造方法传入。
            super(msg);
        }
    }

    系统定义的异常,在程序中遇到时是由系统自动抛出的,但是 在抛出自定义异常时,需要用户使用throw语句自己抛出,其格式 如下:

        throw new 自定义的异常类类名([参数列表]);

    class MyException extends Exception{    
        public MyException(String msg){
            super(msg) ;    
        }
    }
    public class DefaultException{    
        public static void main(String args[]){
            try{
                throw new MyException("自定义异常。") ;     
            }catch(Exception e){
                System.out.println(e) ;
            }
        }
    }

  • 相关阅读:
    js获取元素位置和style的兼容性写法
    javascript正则表达式---正向预查
    Typescript学习笔记(五) 模块机制
    Typescript学习笔记(四)class 类
    Typescript学习笔记(三)变量声明及作用域
    Typescript学习笔记(二)枚举
    Typescript学习笔记(一)基础类型
    tar命令
    linux的nohup命令的用法。
    vue.js移动端app实战1
  • 原文地址:https://www.cnblogs.com/l666/p/9657399.html
Copyright © 2011-2022 走看看