- Throw 抛异常 (不推荐一旦出现异常整个程序直接干掉)
2.Try catch 整体 try catch
一旦发生异常还可以继续执行
public class ExceptionDemo2 {
public static void main(String[] args) {
System.out.println("程序开始");
parseTime("2011-11-11 11:11:11");
System.out.println("程序结束");
}
public static void parseTime(String data) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy*MM-dd HH:mm:ss");
Date d = sdf.parse(data);
System.out.println(d);
InputStream is = new FileInputStream("E:/meinv.jpg");
} catch (ParseException | FileNotFoundException e) {
e.printStackTrace();
}
}
}
控制台:
3. Throw和 trycatch 两者结合
理论上最好的方法
package exception_handle;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExceptionDemo3 {
public static void main(String[] args) {
System.out.println("程序开始");
try {
parseTime("2011-11-11 11:11:11");
System.out.println("功能操作成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("功能操作失败");
}
System.out.println("程序结束");
}
public static void parseTime(String data) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(data);
System.out.println(d);
InputStream is = new FileInputStream("E:/meinv.jpg");
}
}
4.运行时候的异常
可以不处理
代码:
/**
* 运行时异常处理
* 可以不处理 编译不报错
* 建议处理只需要在最外层处理就行
*/
public class Test
{
public static void main(String[] args) {
System.out.println("start");
try {
chu(1,0);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end");
}
public static void chu(int a ,int b){
System.out.println(a);
System.out.println(b);
int c = a/b;
System.out.println(c);
}
}
5.异常处理使代码更稳健
(1).案列题目:
循环输入价格直到输入正确的 不能负数,异常数
(2).代码:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true){
try {
System.out.println("输入合法的价格");
String priceStr = scanner.nextLine();
//转换成double 价格
double a = Double.valueOf(priceStr);
if (a>0){
System.out.println("定价"+a);
break;
}else {
System.out.println("价格必须是正数");
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("用户输入的值不正常");
}
}
}
6.自定义异常
- 自定义异常代码
/**
* 自定义编译异常
*
* 1继承 Exception
* 2重写构造器
*/
public class itheimaAgeIlleagalException extends Exception {
public itheimaAgeIlleagalException() {
}
public itheimaAgeIlleagalException(String message) {
super(message);
}
}
2 .列子代码
public class ExceptionDemo {
public static void main(String[] args) {
try {
checkAge(-34);
} catch (itheimaAgeIlleagalException e) {
e.printStackTrace();
}
}
public static void checkAge(int age) throws itheimaAgeIlleagalException {
if (age<0 || age>200){
//抛出去异常
//throw 在方法内部直接创建一个异常 并从此点抛出
//throws :用在方法声明上 抛出方法内部异常
throw new itheimaAgeIlleagalException(age+"年龄瞎搞!");
}else {
System.out.println("年龄合法:可以购买");
}
}
}