异常就是在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序。
异常不是错误
程序中关键的位置有异常处理,提高程序的稳定性
Java的异常处理是通过5个关键字来实现的
try:尝试,把有可能发生错误的代码放在其中,必须有
catch:捕获,当发生异常时执行
finally:最终,不管是否有异常都将执行
throw:抛出,引发异常
throws:抛出多个,声明方法将产生某些异常


package com.zhangguo.chapter6.d1;
import java.util.Scanner;
public class Exception1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//int i=input.nextInt();
int i=Integer.parseInt(input.next());
System.out.println("您输入的是:"+i);
System.out.println("程序结束了");
}
}
异常处理:
package com.zhangguo.chapter6.d1;
import java.util.Scanner;
public class Exception1 {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int i = Integer.parseInt(input.next());
System.out.println("您输入的是:" + i);
} catch (Exception exp) {
System.out.println("发生异常了:" + exp.getMessage());
}
System.out.println("程序结束了");
}
}
结果:

finally在任何情况下都将执行,正常时会执行,不正常也会执行
package com.zhangguo.chapter6.d1;
import java.util.Scanner;
public class Exception1 {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int i = Integer.parseInt(input.next());
System.out.println("您输入的是:" + i);
} catch (Exception exp) {
System.out.println("发生异常了:" + exp.getMessage());
}finally {
System.out.println("输入结束");
}
System.out.println("程序结束了");
}
}
结果:
1
您输入的是:1
输入结束
程序结束了
如果用户输入是的xyz

常用的异常
package com.zhangguo.chapter6.d1;
public class Exception2 {
public static void main(String[] args) {
try {
System.out.println(div(30,3));
} catch (Exception e) {
//输出异常的堆栈信息
e.printStackTrace();
}
try {
System.out.println(div(3,0));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//throws 声明方法将可能抛出异常
public static int div(int n1,int n2) throws Exception{
if(n2==0){
//抛出异常
throw new Exception("除数不能为零");
}
return n1/n2;
}
}
运行结果:

public class ArithmeticException extends RuntimeException {
private static final long serialVersionUID = 2256477558314496007L;
/**
* Constructs an {@code ArithmeticException} with no detail
* message.
*/
public ArithmeticException() {
super();
}
/**
* Constructs an {@code ArithmeticException} with the specified
* detail message.
*
* @param s the detail message.
*/
public ArithmeticException(String s) {
super(s);
}
}

原文:http://www.cnblogs.com/zhanglixina/p/7694757.html