什么是异常?
异常就是代表程序出现问题
Error:代表系统级别的错误(属于严重问题),也就是说系统一旦出现问题,sun公司会把这些问题封装成Error对象给出来,说白了,Error是给sun公司自己用的,不是给我们程序员用的,因此我们开发人员不用处理。
Exception :叫异常,它代表的才是程序可能出现的问题,所以,我们程序员通常会用Exception以及它的孩子来封装程序出现的问题。
运行时异常:RuntimeException及其子类,编译阶段不会出现错误提醒,运行时出现的异常(如:数组索引越界异常)。
编译时异常:编译时就会出现错误提醒的(如:日期解析异常)
public class ExceptionTest1{
public static void main(String[] args)
{
//Integer.valueOf("abd");
//int [] arr={11,22,33};
System.out.println(arr[5]);
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
}catch(ParseException e ){
e.printStackTrace();
}
}
}
自定义异常
Java 无法为这个世界上全部问题都提供异常类来代表,如果企业自己的某种问题,想通过异常来表示,以便用异常来管理该问题,那就需要自己来定义异常类。
自定义运行时异常 |
---|
定义一个异常类型RuntimeException |
重写构造器 |
通过throw new 异常类(xxx)来创建对象并输出。 |
编译阶段不报错,提醒不强烈,运行时才可能出现. |
public class ExceptionTest2{
public static void main(String[] args)
{
try{ //需求:保存一个合法的年龄
saveAge(160);
}catch(Exception e)
{
e.printStackTrace();
System.out.println("底层出现了bug!");
}
}
public static void saveAge(int age)
{
if(age>0 && age< 150)
{
System.out.println("年龄被成功保存" + age);
}else{
///用一个异常对象封装这个问题
throw new AgeIllageRuntimeException("/age is illegal ,your age is " + age);
}
}
}
public class AgeIllegalRuntimeException extends RuntimeException{
public AgeIllegalRuntimeExcepting(){
}
public AgeIllegelRuntimeException(String message)
{
super(message);
}
}
自定义编译时异常 |
---|
定义一个异常类继承Exception |
重写构造器 |
通过throw new 异常类(xxx)来创建异常对象并抛出。 |
编译阶段就报错,提醒更加强烈 |
异常处理
1、捕获异常,记录异常并响应合适的信息给用户。
示例如下
public class ExceptionTest3{
public static void main(String args)
{
try{
}catch(FileNotFoundException e){
System.out.println("您要找的文件不存在!!");
e.printStackTrace();
}catch(ParseException e){
System.out.println("您要解析的时间有问题了!");
e.printStackTrace();
}
}
public static void test1() throws FileNotFoundException,parseException{
SimpleDateFormat sdf = newSimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date d = sdf.parse("2028-11-11 10:24:11");
System.out.println(d);
test2();
}
public static void test2() throws FileNotFoundException{
InputStream is = new FileInputStream("D:/meini.png");
}
}
2、捕获异常,尝试重新修复。
示例如下
public class ExceptionTest4{
public static void main(String[] args)
{ //需求:调用一个方法,让用户输入一个合适的价格返回为止
while(true)
{
try{
System.out.println(getMoney());
break;
}catch(Exception)
{
System.out.println("请您输入合法的数字!!");
}
}
}
public static double getMoney(){
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("请您输入合适的价格!");
double money = sc.nextDouble();
if(money >= 0)
{
return money;
}else
{
System.out.println("您输入的价格是不合适的")
}
}
}
}