程序运行过程中出现的不正常现象
这里主要讲解第二类:编译通过,程序运行时不正常
例:输入一个数字,打印这个数字的平方
class Test{
public static void main(String[] args){
String str = javax.swing.JOptionPane.showInputDialog("输入数字");
int N = Integer.parseInt(str);
int R = N*N;
System.out.println("结果是:"+R);
}
}
常见的异常类型有哪些?
1、ArithmeticException:算术异常,如除数为0
2、ArrayIndexOutOfBoundsException:数组越界
3、NullPointerException:未分配内存异常
4、NumberFormatException:数字格式异常
…
class Test{
public static void main(String[] args){
//int a = 1;int b = 0;int c = a/b;
//int[] a =new int[5];
}
}
public class Test {
public static void main(String[] args) {
String str = javax.swing.JOptionPane.showInputDialog("输入数字");
try {
int N = Integer.parseInt(str);
int R = N*N;
System.out.println("结果是:"+R);
}catch(Exception e) {System.out.println("输入异常");}
}
}
public class Test {
public static void main(String[] args) {
String str = javax.swing.JOptionPane.showInputDialog("输入数字");
try {
int N = Integer.parseInt(str);
int R = N*N;
System.out.println("结果是:"+R);
}catch(NumberFormatException e) {System.out.println("数字格式异常");}
catch(Exception e) {System.out.println("输入异常");}
}
}
public class Test {
public static void main(String[] args) {
try {
System.out.println("访问数据库");
System.out.println("处理数据");
int a = 10/0;
}
catch(Exception e) {System.out.println("数据库链接异常");}
finally {
System.out.println("关闭数据库");
}
}
}
public class Test {
public static void main(String[] args) {
for(int i= 0;i <= 100;i++)
{
try {
System.out.println("try");
if(i==1) break;
}catch(Exception e) {}
finally {System.out.println("finally");}
}
}
}
class Test{
public static void main (String[] args) {
while(true){
try{
String str = javax.swing.JOptionPane.showInputDialog("请输入");
double d = Double.parseDouble(str);
double result = d * d;
System.out.println("平方是:" + result);
break;
}catch(Exception e){
javax.swing.JOptionPane.showMessageDialog(null,"输入错误");
}
}
}
}
案例:编写一个函数,setAge,输入一个年龄,如果年龄在0-100之间,返回年龄;否则返回“年龄错误”。
package customer;
public class Test {
public int setAge(int age) throws Exception
{
if(age < 0||age > 100)
{
Exception e = new Exception("年龄错误");
throw e;
}
else
{
System.out.println(age);
return age;
}
}
public static void main(String[] args) throws Exception {
Test t = new Test();
t.setAge(500);
}
// public static void main(String[] args){
// Test t = new Test();
// try {
// t.setAge(500);
// }catch(Exception e) {System.out.println(e.getMessage());}
//
// }
}
class AgeException extends Exception{
String msg;
AgeException(String msg){ this.msg = msg; }
public String getMessage() { return msg; }
}
class Test{
int setAge(int age) throws AgeException{
if(age>100||age<0){
throw new AgeException("年龄错误:" + age);
}
return age;
}
void callSetAge() throws AgeException{
int a = setAge(1000);
}
public static void main (String[] args) {
Test t = new Test();
try{t.callSetAge();}
catch(AgeException ae){ System.out.println(ae.getMessage()); }
}
}