- Java中try、catch和finally实现异常处理
try——catch及try——catch——finally
package com.imooc;
import java.util.Scanner;
public class Auto {
public static void main(String []args){
System.out.println("请输入您的年龄");//输入hello
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
System.out.println("十年后" + (age + 10) + "岁");
System.out.println("你应该输入整数");
System.out.println("程序结束");
}
}
运行结果为:
package com.imooc;
import java.util.Scanner;
public class Auto {
public static void main(String []args){
try {
System.out.println("请输入您的年龄");//输入hello
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
System.out.println("十年后" + (age + 10) + "岁");
} catch (Exception e) {
System.out.println("你应该输入整数");
}
System.out.println("程序结束");
}
}
运行结果为:
try会抛出很多种类型的异常????
package com.imooc;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Auto {
public static void main(String []args){
Scanner sc = new Scanner(System.in);
try {
System.out.println("请输入第一个数:");//输入hello
int one = sc.nextInt();
System.out.println("请输入第二个数:");//输入hello
int two = sc.nextInt();
System.out.println("两个数相除结果是:"+one/two);
} catch (InputMismatchException e) {
System.out.println("你应该输入整数");
}catch(ArithmeticException e){
System.out.println("除数不能为0");
}
System.out.println("程序结束");
}
}
运行结果为:
package com.imooc;
public class Auto {
public static void main(String []args){
Auto au=new Auto();
int result=au.test();
System.out.println("test()方法,执行完毕!返回值:"+result);
}
public int test(){
int diviler=10;
int result=100;
try {
while (diviler > -1) {
diviler--;
result = result + 100 / diviler;
}
return result;
} catch (Exception e) {
System.out.println("抛出异常");
return -1;
}
}
}
运行结果为:
package com.imooc;
public class Auto {
public static void main(String []args){
Auto au=new Auto();
int result=au.test();
System.out.println("test()方法,执行完毕!返回值:"+result);
}
public int test(){
int diviler=10;
int result=100;
try {
while (diviler > -1) {
diviler--;
result = result + 100 / diviler;
}
return result;
} catch (Exception e) {
System.out.println("抛出异常");
return result=999;
}finally{
System.out.println("finally");
}
}
}
运行结果为:
**********try 语句块不可以独立存在,必须与 catch 或者 finally 块同存*************
- Java中的异常抛出以及自定义异常
Java中的异常抛出
throw——将产生的异常抛出(动作)
throws——声明将要抛出种类型的异常(声明)
自定义异常
package com.imooc;
public class DrunkException extends Exception{
public DrunkException(){
}
public DrunkException(String message){
super(message);
}
}
****自定义异常类的父类可以是( Exception)*********
解析:Exception 是异常类,自定义异常要继承于 Exception 类或者其子类
- Java中的异常链
package com.imooc;
public class DrunkException extends Exception{
public DrunkException(){
}
public DrunkException(String message){
super(message);
}
}
第一种写法:
package com.imooc;
public class ChainTest {
/*
* test1():抛出 “喝大了”异常
* test2():调用test1捕获“喝大了”异常,并且包装成运行时异常,继续抛出
* main()方法中,调用test2(),尝试捕获test2()方法抛出异常
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ChainTest ct=new ChainTest();
try {
ct.test2();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void test1() throws DrunkException{
throw new DrunkException("开车不能喝酒");
}
public void test2(){
try {
test1();
} catch (Exception e) {
// TODO: handle exception
RuntimeException newExc=new RuntimeException("司机一滴酒,亲人两行泪~~~~~");
newExc.initCause(e);
throw newExc;
}
}
}
运行结果为:
另一种写法:
package com.imooc;
public class ChainTest {
/*
* test1():抛出 “喝大了”异常
* test2():调用test1捕获“喝大了”异常,并且包装成运行时异常,继续抛出
* main()方法中,调用test2(),尝试捕获test2()方法抛出异常
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ChainTest ct=new ChainTest();
try {
ct.test2();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void test1() throws DrunkException{
throw new DrunkException("开车不能喝酒");
}
public void test2(){
try {
test1();
} catch (Exception e) {
// TODO: handle exception
RuntimeException newExc=new RuntimeException(e);
//newExc.initCause(e);
throw newExc;
}
}
}
运行结果为:
*捕获到的异常,可以在当前方法的 catch 块中处理,也可抛出给调用者去处理
*Exception 的父类是 Throwable
*使用 try-catch-finally 语句捕获并处理异常
*可以使用 throw 语句抛出异常
- 经验总结
1.处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
2.在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
3.对于不确定的代码,也可以加上try-catch,处理潜在的异常
4.尽量去处理异常,切忌只是简单的调用printStackTrace()去打印输出
5.具体如何处理异常,要根据不同的业务需求和异常类型去决定
6.尽量添加finally语句块去释放占用 的资源
小练习操作
模拟借书系统
要求:
1.定义字符串数组保存图书信息
2.提示用户输入,分别按"书名"和"图书序号"查找图书
3.根据输入信息进行适当的异常处理
a.如果输入类型错误,抛出"错误命令异常",并提示重新输入
b.如果书名不存在,抛出"图书不存在异常",并提示重新输入
c.如果图书序号超过字符串数组范围,抛出"图书不存在异常",并提示重新输入
package com.imoc;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Book {
private String[] book = {new String("高数"), new String("数据结构")};
private Scanner c = null;
private boolean flagNotFound = true;
private int searchMethod() throws WrongCommandException{
int k = 0;
System.out.println("请输入命令:1-按照名称查找图书;2-按照序号查找图书");
try{
c = new Scanner(System.in);
k = c.nextInt();
if (k == 1 || k == 2){
}
else{
System.out.println("命令输入错误!请根据提示输入数字命令!");
throw new WrongCommandException("命令输入错误!");
}
}catch (InputMismatchException e){
throw new WrongCommandException("命令输入错误!");
}
return k;
}
private int searchBookByName() throws BookDoesNotExistException{
int i = 0;
System.out.println("请输入图书名称:");
c = new Scanner(System.in);
String s = c.next();
for(i = 0; i < book.length; i++){
if(s.equals(book[i])){
return i;
}
}
throw new BookDoesNotExistException("图书不存在!");
}
private int searchBookByNumber() throws BookDoesNotExistException{
int i = 0;
System.out.println("请输入图书序号:");
try{
c = new Scanner(System.in);
int s = c.nextInt();
for(i = 0; i < book.length; i++){
if(s == i+1){
return i;
}
}
throw new BookDoesNotExistException("图书不存在!");
}catch (Exception e){
throw new BookDoesNotExistException("图书不存在!");
}
}
public void processing(){
int bookNumber;
int k = 0;
while(flagNotFound){
try{
k = searchMethod();
if(k == 1){
try{
bookNumber = searchBookByName();
flagNotFound = false;
System.out.println("book:"+book[bookNumber]);
}catch (BookDoesNotExistException e){
System.out.println("图书不存在!");
flagNotFound = true;
}
}
else if (k == 2){
try{
bookNumber = searchBookByNumber();
flagNotFound = false;
System.out.println("book:"+book[bookNumber]);
}catch (BookDoesNotExistException e){
System.out.println("图书不存在!");
flagNotFound = true;
}
}
}catch(WrongCommandException e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
flagNotFound = true;
}
}
if(c!=null)
c.close();
}
}
package com.imoc;
public class WrongCommandException extends Exception{
public WrongCommandException(){
}
public WrongCommandException(String Message){
super(Message);
}
}
package com.imoc;
public class BookDoesNotExistException extends Exception {
public BookDoesNotExistException(){}
public BookDoesNotExistException(String Message) {
// TODO Auto-generated constructor stub
super(Message);
}
}
package com.imoc;
public class BookManagement {
public static void main(String[] args) {
// TODO Auto-generated method stub
Book book1=new Book();
book1.processing();
}
}
运行结果为: