java中抛出异常以及自定义异常

这个就是类似于提示你的代码有问题,我觉用处并不是太大。

抛出异常

 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Yichang2 {
	public static void main(String[] args) {
		method();
		method2();
		try {
			method3();//throw并没有解决问题
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void method3() throws ParseException {
		String s = "2048-08-09";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = sdf.parse(s);
		System.out.println(d);
	}
	//编译时异常
	public static void method2() {
		try {			
		String s = "2048-08-09";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = sdf.parse(s);
		System.out.println(d);
		}catch(ParseException e){
			e.printStackTrace();
		}
	}
	//运行时时异常
	public static void method() {
		try {
			int[] a = {1,2,3};
			System.out.println(a[3]);	
		}catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();//这个方法在输出的信息是最全的一般都用它
		}
	}
}

输出:

java.lang.ArrayIndexOutOfBoundsException: 3
    at com.yichang.test.Yichang2.method(Yichang2.java:39)
    at com.yichang.test.Yichang2.main(Yichang2.java:9)
Sun Aug 09 00:00:00 CST 2048
Sun Aug 09 00:00:00 CST 2048


自定义异常

public class ScoreException extends Exception{

	public ScoreException() {
	}
	public ScoreException(String message) {
		super(message);
	}
}
public class Teacher {
	public void checkScore(int score)throws ScoreException{
		if(score<0||score>100) {
			throw new ScoreException("你给的分数有误");
		}else{
			System.out.println("分数正常");
		}
	}
}
import java.util.*;
public class Teachertest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入分数:");
		int score = sc.nextInt();
		Teacher t = new Teacher();
		try {
			t.checkScore(score);
		} catch (ScoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

输出:

请输入分数:
120
com.yichang.test.ScoreException: 你给的分数有误
    at com.yichang.test.Teacher.checkScore(Teacher.java:6)
    at com.yichang.test.Teachertest.main(Teachertest.java:10)
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值