java学习日记之 异常

异常处理1:try和catch捕获异常

package com.MissXu.blogTest;

import java.util.Scanner;

public class ExceptionTest {

	public static void main(String[] args) {
		
		System.out.println("---------begin---------");
		//背单词啦:divisor被除数、dividend除数、quotient商
		try {
			Scanner scan = new Scanner(System.in);
			System.out.print("Please input the divisor :");
			int divisor = Integer.parseInt(scan.nextLine()); //接收第一个整数作为被除数
			System.out.print("Please input the dividend :");
			int dividend = Integer.parseInt(scan.nextLine()); //接收第二个整数作为除数
			int quotient = divisor / dividend; //商
			System.out.println("result : " + quotient);
		} catch (NumberFormatException e) {
			System.out.println("数据格式异常:参数必须是数字!" + e);
		}catch (ArrayIndexOutOfBoundsException e){
			System.out.println("参数个数不对,必须是两个!" + e);
		}catch (ArithmeticException  e){
			System.out.println("除数不能为零!" + e);
		}catch(Exception e){ //为了防止漏写一些异常,可以加上Exception,但这个Exception必须写在最后
			System.out.println("发生了异常!" + e);
		}finally{
			System.out.println("I'll run whether there is a exception. "); //输出证明:不管异常与否程序都运行了
		}
		
		System.out.println("---------end---------");

	}

}


异常处理2:throw向上抛出异常

这里是一个标准的异常处理流程示例:

package com.MissXu.blogTest;

class Math{
	public int div(int i,int j) throws Exception{
		System.out.println("--------除法之前--------");
		int t=0;
		try{	
			t=i/j;
		}catch(Exception e){
			throw e;
		}finally{
			System.out.println("--------除法之后--------");
		}
			return t;
	}
}

public class ThrowTest {
	public static void main(String[] args) {
		Math m=new Math();
		try{
			int t=m.div(10,0);
			System.out.println(t);
		}catch(Exception e){
			System.out.println(e);
		}		
	}
}

你可能感兴趣的:(java,异常)