

package 测试;
import javax.swing.*;
class AboutException {
public static void main(String[] a)
{
int i=1, j=0, k;
k=i/j;
try
{
k = i/j; // Causes division-by-zero exception
//throw new Exception("Hello.Exception!");
}
catch ( ArithmeticException e)
{
System.out.println("被0除. "+ e.getMessage());
}
catch (Exception e)
{
if (e instanceof ArithmeticException)
System.out.println("被0除");
else
{
System.out.println(e.getMessage());
}
}
finally
{
JOptionPane.showConfirmDialog(null,"OK");
}
}
}




ArrayIndexOutOfBoundsException/内层try-catch
发生ArithmeticException


ArrayIndexOutOfBoundsException/外层try-catch


当try不出错时,只运行finally


finally语句块不一定会执行,当Try语句中throw一个错误时fin被catch语句截获,并在catch语句中有exit(0)时,finally语句不会被执行。

package 考试成绩;
import java.util.Scanner;
// 陈天时 20163591 信1605-3
public class KaoShiChengJi
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
for(;;)//无限循环
{
System.out.println("请输入一门考试的成绩:");
String I=input.next();
int i=Integer.parseInt(I);
try
{
if(i>0&&i<60)
{
System.out.println("不及格");
continue;//跳出循环
}
else if(i>=60&&i<70)
{
System.out.println("及格");
continue;
}
else if(i>=70&&i<80)
{
System.out.println("中");
continue;
}
else if(i>=80&&i<90)
{
System.out.println("良");
continue;
}
else if(i>=90&&i<=100)
{
System.out.println("优");
continue;
}
else
{
System.out.println("您输入的成绩超出范围,请重新输入!");
}
}
catch(NumberFormatException e)
{
System.out.println("您输入的成绩超出范围,请重新输入!");
}
continue;
}
}
}
原文:http://www.cnblogs.com/cts1234/p/7846432.html