异常处理
来源:互联网 发布:有肉的耽美网络剧 编辑:程序博客网 时间:2024/04/27 14:51
Java异常
在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅等等。
异常
在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)
Java程序在执行过程中所发生的异常事件可分为两类:
Error: Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。一般不编写针对性的代码进行处理。
代码演示:
package com.it18zhang.java1;
public class TestError {
public static void main(String[] args) {
//java.lang.StackOverflowError
//main(args);
//java.lang.OutOfMemoryError
byte[] b = new byte[1024*1024*600];
}
}
Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:
空指针访问
试图读取不存在的文件
网络连接中断
代码演示
@Test
public void test1(){
Scanner s = new Scanner(System.in);
int i = s.nextInt();
System.out.println(i);
}
解决方法
对于这些错误,一般有两种解决方法:
一是遇到错误就终止程序的运行。
另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。
捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。比如:除数为0,数组下标越界等
分类:编译时异常和运行时异常
数组下标越界的异
常:ArrayIndexOutOfBoundsException
@Test
public void test2(){
int[] i = new int[10];
//System.out.println(i[10]);
System.out.println(i[-10]);
}
算术异常:
ArithmeticException
@Test
public void test3(){
int i = 10;
System.out.println(i / 0);
}
类型转换异常:ClassCastException
@Test
public void test4(){
Object obj = new Date();
String str = (String)obj;
//String str1 = (String)new Date();
}
空指针异常:NullPointerExcetion
@Test
public void test5(){
//Person p = new Person();
//p = null;
//System.out.println(p.toString());
String str = new String("AA");
str = null;
System.out.println(str.length());
}
/*一、异常的体系结构
* java.lang.Throwable
* |-----Error:错误,程序中不进行处理
* |-----Exception:异常,要求在编写程序时,就要考虑到对这些异常的处理
* |-----编译时异常:在编译期间会出现的异常(执行javac.exe命令时,出现异常)
* |-----运行时异常:在运行期间出现的异常(执行java.exe命令时,出现异常)
*
* 当执行一个程序时,如果出现异常,那么异常之后的代码就不再执行!
*/
编译时异常
@Test
public void test6(){
//FileInputStream fis = new FileInputStream(new File("hello.txt"));
//int b;
//while((b = fis.read()) != -1){
//System.out.println((char)b);
//}
//fis.close();
}
1.运行时异常
是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。
2.编译时异常
是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。编译器要求java程序必须捕获或声明所有编译时异常。
对于这类异常,如果程序不处理,可能会带来意想不到的结果
异常处理机制
Java提供的是异常处理的抓抛模型
/*
* 二、如何处理Exception的异常
* Java提供的是异常处理的抓抛模型
* 1."抛":当我们执行代码时,一旦出现异常,就会在异常的代码处生成一个对应的异常类型的对象,并
* 将此对象抛出。(自动抛出 /手动抛出)
* >一旦抛出此异常类的对象,那么程序就终止执行
* >此异常类的对象抛给方法的调用者。
* 2."抓":抓住上一步抛出来的异常类的对象。如何抓?即为异常处理的方式
* java 提供了两种方式用来处理一个异常类的对象。
* 处理的方式一:
* try{
* //可能出现异常的代码
* }catch(Exception1 e1){
* //处理的方式1
* }catch(Exception2 e2){
* //处理的方式2
* }finally{
* //一定要执行的代码
* }
* 注:1.try内声明的变量,类似于局部变量,出了try{}语句,就不能被调用
* 2.finally是可选的。
* 3.catch语句内部是对异常对象的处理:
* >getMessage(); printStackTrace();
* 4.可以有多个catch语句,try中抛出的异常类对象从上往下去匹配catch中的异常类的类型,一旦满足
* 就执行catch中的代码。执行完,就跳出其后的多条catch语句
* 5.如果异常处理了,那么其后的代码继续执行。
* 6.若catch中多个异常类型是"并列"关系,孰上孰下都可以。
* 若catch中多个异常类型是"包含"关系,须将子类放在父类的上面,进行处理。否则报错!
* 7.finally中存放的是一定会被执行的代码,不管try中、catch中是否仍有异常未被处理,以及是否有return语句。
* 8.try-catch是可以嵌套的。
*
* 三、对于运行时异常来说,可以不显式的进行处理。
* 对于编译时异常来说,必须要显式的进行处理。
*/
public class TestException1 {
// 编译时异常
@Test
public void test6() {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File("hello.txt"));
int b;
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}
} catch (FileNotFoundException e1) {
System.out.println("文件找不到了!");
} catch (IOException e1) {
System.out.println(e1.getMessage());
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 常见的运行时异常
// 4.空指针异常:NullPointerExcetion
@Test
public void test5() {
// Person p = new Person();
// p = null;
// System.out.println(p.toString());
try {
String str = new String("AA");
str = null;
System.out.println(str.length());
} catch (Exception e) {
// e.printStackTrace();
System.out.println("出现空指针的异常了");
}
}
// 3.类型转换异常:ClassCastException
@Test
public void test4() {
try {
Object obj = new Date();
String str = (String) obj;
} catch (ClassCastException e) {
System.out.println("出现类型转换的异常了");
//System.out.println(10 / 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("hello!美女!");
}
// String str1 = (String)new Date();
}
// 2.算术异常:ArithmeticException
@Test
public void test3() {
try {
int i = 10;
System.out.println(i / 0);
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
// 1.数组下标越界的异常:ArrayIndexOutOfBoundsException
@Test
public void test2() {
try {
int[] i = new int[10];
// System.out.println(i[10]);
System.out.println(i[-10]);
} catch (Exception e) {
System.out.println("出现异常了!");
}
}
@Test
public void test1() {
Scanner s = new Scanner(System.in);
try {
int i = s.nextInt();
System.out.println(i);
} catch (InputMismatchException e) {
System.out.println("出现类型不匹配的异常了!");
}
}
}
finally面试讲解
public class TestFinally {
public static void main(String[] args) {
int i = method1();
System.out.println(i);
}
public static int method1(){
try{
System.out.println(10/0);
return 1;
}catch(Exception e){
e.printStackTrace();
return 3;
}finally{
System.out.println("我是帅哥!");
return 2;
}
}
}
Java程序的执行过程中如出现异常,会生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。
如果一个方法内抛出异常,该异常对象会被抛给调用者方法中处理。如果异常没有在调用者方法中处理,它继续被抛给这个调用方法的上层方法。这个过程将一直继续下去,直到异常被处理。这一过程称为捕获(catch)异常。
程序员通常只能处理Exception,而对Error无能为力
异常处理是通过try-catch-finally语句实现的。
try{
...... //可能产生异常的代码
}
catch( ExceptionName1 e ){
...... //当产生ExceptionName1型异常时的处置措施
}
catch( ExceptionName2 e ){
...... //当产生ExceptionName2型异常时的处置措施
}
[ finally{
...... //无论是否发生异常,都无条件执行的语句
} ]
捕获异常的有关信息:
与其它对象一样,可以访问一个异常对象的成员变量或调用它的方法。
getMessage() 获取异常信息,返回字符串
printStackTrace() 获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。
try
捕获异常的第一步是用try{…}语句块选定捕获异常的范围,将可能出现异常的代码放在try语句块中。
catch (Exceptiontype e)
在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象。
finally
捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得在控制流转到程序的其它部分以前,能够对程序的状态作统一的管理。
不论在try代码块中是否发生了异常事件,catch语句是否执行,catch语句是否有异常,catch语句中是否有return,finally块中的语句都会被执行。
finally语句和catch语句是任选的
声明抛出异常是Java中处理异常的第二种方式
如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。
在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。
声明抛出异常举例:
public void readFile(String file) throws FileNotFoundException {
……
// 读文件的操作可能产生FileNotFoundException类型的异常
FileInputStream fis = new FileInputStream(file);
..……
}
人工抛出异常
Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要人工创建并抛出。
首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)。
IOException e = new IOException();
throw e;
可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:
throw new String("want to throw");
//1.手动的抛出一个异常的例子
//2.抛出的异常类型:若是RuntimeException,可以不显式的处理
//若是一个Exception,必须要显式的处理。
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle(2.1);
Circle c2 = new Circle(2.1);
try {
System.out.println(c1.compareTo(c2));
System.out.println(c1.compareTo(new String("AA")));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Circle{
private double radius;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public Circle(double radius) {
super();
this.radius = radius;
}
//比较两个圆的半径的大小。
public int compareTo(Object obj)throws Exception{
if(this == obj){
return 0;
}
else if(objinstanceof Circle){
Circle c = (Circle)obj;
if(this.radius > c.radius){
return 1;
}else if(this.radius == c.radius){
return 0;
}else{
return -1;
}
}else{
//return -2;
//手动的抛出一个异常
throw new Exception("传入的类型有误!");
//throw new String("传入的类型有误!");
//throw new MyException("传入的类型有误!");
}
}
}
如何手动抛出一个异常
//如何自定义一个异常类
//1.自定义的异常类继承现有的异常类
//2.提供一个序列号,提供几个重载的构造器
public class MyExceptionextends Exception{
static final long serialVersionUID = -70348975766939L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
创建用户自定义异常类
一般地,用户自定义异常类都是RuntimeException的子类。
自定义异常类通常需要编写几个重载的构造器。
自定义的异常类对象通过throw抛出。
自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。
面试题
public class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("进入方法A");
throw new RuntimeException("制造异常");
} finally {
System.out.println("用A方法的finally");
}}
static int methodB() {
try {
System.out.println("进入方法B");
return 1;
} finally {
System.out.println("调用B方法的finally");
return 2;
}}
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
int i = methodB();
System.out.println(i);
}
}
编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算两数相除。
对数据类型不一致(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef自定义的异常)进行异常处理。
提示:
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10
//args[0]=“20”args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。如int a=Interger.parseInt(“314”); //a=314;
/*
* 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算两数相除。
对数据类型不一致(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef自定义的异常)进行异常处理。
提示:
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10
//args[0]=“20”args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。如int a=Interger.parseInt(“314”);//a=314;
*/
public class EcmDef {
public static void main(String[] args) {
try{
int i = Integer.parseInt(args[0]);//被除数
int j = Integer.parseInt(args[1]);//除数
ecm(i,j);
}catch(NumberFormatException e){
System.out.println("输入的数据类型不一致");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("缺少命令行参数");
}catch(ArithmeticException e){
System.out.println("分母为零了");
}catch(EcDef e){
System.out.println(e.getMessage());
}
}
public static void ecm(int i,int j)throws EcDef{
if(i < 0 || j < 0){
throw new EcDef("您输入的数值存在负数!");
}
System.out.println(i / j);
}
}
//自定义异常类
class EcDef extends Exception{
static final long serialVersionUID = -3387524229948L;
public EcDef(){
}
public EcDef(String msg){
super(msg);
}
}
- 异常处理+异常+处理异常+自定义异常
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 虚拟机模拟搭建VMware虚拟化平台
- C++11 raw strings literals tutorial
- IOCP 二进制协议 分包
- ——Character类、正则表达式、Math类、DateFormat类、
- 程序员为什么不适用一般的绩效考核
- 异常处理
- 字符串反转
- 磁盘基础知识笔记
- editText 一开始不自动对焦
- 密码技术之对称加密
- nexus端口设置
- 使用chrome浏览器查看当前HTTP头
- jQuery_包裹节点
- 更新界面方式