zoukankan      html  css  js  c++  java
  • Java异常处理

    Java程序出现异常时,为了避免程序中断,可以使用try...catch语句捕获异常

    package com.jike.exception;
    class Exc{
    	int a=10;
    	int b=10;
    }
    public class test01 {
    	public static void main(String[] args) {
    		int tem=0;
    		Exc exc=null;
    		exc=new Exc();
    		try {
    			tem=exc.a/exc.b;
    			System.out.println(tem);
    		}catch (NullPointerException e) {
    			System.out.println("空指针异常:"+e);
    		}catch (ArithmeticException e) {
    			System.out.println("算数异常:"+e);
    		}finally {
    			System.out.println("程序退出");
    		}
    		
    	}
    }
    

     在定义一个方法的时候可以使用throws关键字声明,使用throws声明的方法不处理异常,将异常传递给方法的调用者处理:

    package com.jike.exception;
    
    public class test02 {
    
    	public static void main(String[] args){
    		// TODO Auto-generated method stub
    		try {
    			tell(10,0);
    		} catch (Exception e) {
    			System.out.println("算术异常:"+e);
    		}
    	}
    	public static void tell(int a,int b)throws ArithmeticException {
    		int tem=0;
    		tem=a/b;
    		System.out.println(tem);
    	}
    
    }
    

     输出:

    算术异常:java.lang.ArithmeticException: / by zero
    

     throw关键字抛出一个异常,抛出的时候直接抛出异常类的实例化对象即可。

    package com.jike.exception;
    
    public class test03 {
    
    	public static void main(String[] args) {
    		try {
    			throw new Exception("实例化异常对象");
    		} catch (Exception e) {
    			System.out.println(e);
    		}
    	}
    }
    

     输出:

    java.lang.Exception: 实例化异常对象
    

    自定义异常:

    package com.jike.exception;
    class MyException extends Exception{
    	public MyException(String msg) {
    		super(msg);
    	}
    }
    public class test04 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		try {
    			throw new MyException("自定义异常");
    		} catch (MyException e) {
    			System.out.println(e);
    		}
    	}
    }
    

     输出:

    com.jike.exception.MyException: 自定义异常
    
  • 相关阅读:
    已知国内量化平台
    用 python 生成一个简单的词云图
    相似性度量的相关文章
    三种交易系统
    一个均线交易策略的回测
    Python在金融量开源项目列表
    雾霾天出行,如何精确避开“雷区”?2016 SODA数据侠十强
    通达信5分钟.lc5和.lc1文件格式
    STM32的USART中断死循环,形成死机。
    挑战练习6.4 报告编译版本
  • 原文地址:https://www.cnblogs.com/zhhy236400/p/10436623.html
Copyright © 2011-2022 走看看