java语言基础入门——异常处理

为什么要进行异常处理?在程序设计中,错误通常分为两类,一类编译错误,一类运行错误。编译错误很容易被发现,而运行错误比较难发现,而异常就是一种运行错误。如果不处理好异常很可能会使程序运行时出错崩溃。而异常也分为两种,受检异常和非受检异常。非受检异常是指像错误类型转换,数组越界等程序员的问题造成的,受检异常是指程序运行的外部原因造成的,比如,操作文件、和数据库连接时的异常,其中,受检异常要求必须处理,而非受检异常不强制要求处理,因为它本身是可以避免的。

java异常处理机制提供了try、catch、throw、throw、finally五个关键字对异常进行处理。

try为检测程序段中是否有异常存在,catch是将检测到异常与catch()中的参数进行匹配,如果程序段中含有此类异常就进入catch程序段。像switch和case一样,catch可以有多个,并且程序只会进入第一个匹配到的catch程序段内,余下的catch将不再配对,因此一般将参数为子类的catch放前面,父类参数的catch放后面。 另外try和catch需要配套使用,并且这两个可以像if和else一样进行嵌套使用,并且是先处理内部try、catch再处理外部try、catch。

package try_catch;

public class TryDemo01 {

	public static void main(String[] args) {
		int number =0;
		try {
			number=Integer.parseInt(args[0]);
			System.out.println("正常");
			
		} catch (Exception e) {
			System.out.println("非正常");
		}
		System.out.println("您输入的数字为:"+number);

	}

}

package try_catch;

public class NestTryDemo {

	public static void main(String[] args) {
	try {
		int number1=Integer.parseInt(args[0]);
		int number2=Integer.parseInt(args[1]);
		try {
			double result =number1/number2;
			System.out.println(result);
		} catch (Exception e) {
			System.out.println(e.getMessage());//返回返回异常愿意,如/by zero
		}finally{
			System.out.println("内层结束");
		}
	} catch (Exception e) {
		e.printStackTrace();//输出异常类型和原因,如:ArithmeticException:/by zero
	}finally{
		System.out.println("外层结束");
	}
	}

}

package try_catch;

import java.util.InputMismatchException;
import java.util.Scanner;

public class MoreCatchDemo {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		try {
			System.out.println("请输入第一学期总学时");
			int totalTime=in.nextInt();
			System.out.println("请输入第一学期课程数目");
			int totalCourse=in.nextInt();
			System.out.println("第一学期各位课程平均学时为:"+totalTime/totalCourse);
		} catch (InputMismatchException e) {
			System.out.println("输入不为数字");
		}catch (ArithmeticException e) {
			System.out.println("输入科目不能为零");
		}catch (Exception e) {
			System.out.println("发生错误");
		}
		System.out.println("catch完结");

	}

}


throw和throws一般用来进行明确的抛出异常。其中throw语句用来明确的抛出一个异常,一般写于catch语句中,throw必须出现在函数体中,并且程序会在throw语句后立即终止,抛出一个Throwable的对象,后面的语句执行不到,并且在throw语句块内,throw语句后面不能再有语句出现。throws语句用来方法操作中,如果一个方法a可以引发异常,而它本身并不对该异常进行处理,而是抛出该异常给它的调用者,该调用者也可以继续向上抛出异常,直至被处理。其中throws可以抛出多个异常,在进行方法的定义时需要将这些可能出现的异常一一列举出来,并且用逗号分隔。在被throws定义的方法中可以使用throw,但是throws抛出类型要比throw类型范围要大。

package try_catch;

public class ThrowDemo {

	public static void main(String[] args) {
		int number=0;
		try {
			number=Integer.parseInt(args[0]);
		} catch (Exception e) {
			throw new ArrayIndexOutOfBoundsException("数组越界");
		   // System.out.println("throw后语句");
		}

		System.out.println("你输入的数字为:"+number);
	}

}

package try_catch;

public class ThrowsDemo {

	public static void main(String[] args) {
		
       testThrows(args);
	}
	public static void  testThrows(String[] temp) {
		try {
			creatThrow(temp);
		} catch (Exception e) {
			System.out.println("来自createThrow方法的异常");
		}
	}
	public static void creatThrow(String[] temp)throws Exception {
		int number=0;
		number=Integer.parseInt(temp[0]);
		System.out.println("你输入的数字为:"+number);
	}

}

package try_catch;

public class ThrowAndThrowsDemo {

	public static void main(String[] args) {
		testThrow(args);

	}

	public static void testThrow (String[] temp) {
		try {
			creatThrow(temp);
		} catch (Exception e) {
			System.out.println("捕捉到来自createThrow方法的异常");
		}
	}
	public static void creatThrow (String[] tmp)throws Exception {
		int number=0;
		try {
			number=Integer.parseInt(tmp[0]);
		} catch (Exception e) {
			throw new ArrayIndexOutOfBoundsException("数组越界");
		}
		System.out.println("你输入的数字为:"+number);
	}
}


finally关键字主要用在try、catch后面,用来表示无论出现异常与否都会运行的程序段。且finally的代码段先于try的return语句运行,但是在finally中更改try要返回的值并不不起作用。

package try_catch;

public class FinallyDemo {

	public static void main(String[] args) {
		try {
			System.out.println("程序开始");
			int i=10/10;
			System.out.println("除零结束");
		} catch (Exception e) {
			System.out.println("除零出错");
			e.printStackTrace();//打印错误详情
		}
		finally{
			System.out.println("程序结束");
		}

	}

}

package try_catch;

import javax.management.RuntimeErrorException;

public class ReturnExceptionDemo {

	public static void  methonA() {
		try {
			System.out.println("进入方法A");
			throw new RuntimeException("制造异常A");
		} finally{
			System.out.println("A方法的finally");
		}
	}
	public static void   methonB() {
		int temp=2;
		int tempFinally=4;
		try {
			System.out.println("进入方法B");
			
			throw new RuntimeException("制造异常B");
			//return temp;
		} finally{
			temp=3; //并不能改变return temp的值,依然返回2
			System.out.println("B方法的finally");
			//return tempFinally; //使用return可以改变返回的值,使得返回值为4,
			//这是由于finally语句先于try中return语句执行,而一个函数只能执行一次return语句,
			//所以try语句块中return语句被屏蔽了
			
		}
		//return temp;//将return语句放于最后最为合理
	}
	public static void main(String[] args) {
		try {
			methonA();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	//	System.out.println(methonB());
	}

}


getMessage方法和printStackrace 方法:getMessage用来返回出错原因,printStackTrace用来返回异常对象类型和出错原因。

自定义异常类,用户可以自己定义自己的异常类,只需要继承或间接继承Throwable类就可以了,一般选用Exception类作为父类。

package try_catch;

import commonly_class.string;

public class MyException extends Exception {

    public MyException(String string) {
		super(string);
	}
	public static void main(String[] args) {
		try {
			throw new MyException("自定义异常");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

                                                                    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值