07_异常
Exception(异常)
Throwable(可抛的)
Exception(异常,代码写错) Error(错误,不可修复)
1异常有两种:
一.编译期异常:编译的时候需要检查,并一定要写try-catch语句,不写便不能通过的异常
二.运行期异常:编译的时候不检查,不写try-catch语句也能编译通过的异常。
2常用的运行期异常
NumberFormatExcepton:数字格式化异常
示例代码:
public class Test{
public static void main(String args[]){
Try{
int num1 = Integer.parseInt(args[0]);
int num1 = Integer.parseInt(args[0]);
System.out.println(num1 + num2);
}catch(NumberFormatException e){
System.out.println(“请输入合法的整数!”);
}
System.out.println(“程序继续执行......”);
}
}
ArrayIndexOutOfBoundsException数组越界异常
如下代码执行时候就会报出数组越界异常:
public class Test{
public static void main(String args[]){
System.out.println(args[0]);
}
}
NullPointException空指针异常
当一个引用的值为NULL的时候,试图用它来调用方法或者访问属性,就会发生空指针异常。
public class Test{
public static void main(String args[]){
String str;
str = new String(“abc”);
str = null;
str.length();
System.out.println(str);
}
}
3 Try-catch可以捕获多个异常,需要注意的是,必须先捕获子类的异常,再捕获父类的异常。
示例代码:
public class Test{
public static void main(String args[]){
Try{
int num1 = Integer.parseInt(args[0]);
int num1 = Integer.parseInt(args[0]);
System.out.println(num1 + num2);
}catch(NumberFormatException e){
System.out.println(“请输入合法的整数!”);
}catch(ArrayIndexOutfBoundsException e){
System.out.println(“数组越界!”);
}catch(Exception e){
System.out.println(“其他异常!”);
}
System.out.println(“程序继续执行......”);
}
}
4 Throws关键字
把异常抛给调用它的环境。
示例代码:
import java.io.*;
public class Test{
public static void main(String args[]){
T.m();
}
}
class T{
public static void m() throws FileNotFoundException{
FileInputStream is = new FileInputStream(“”);
}
}
5 Throw关键字
手动抛出异常,自定义异常里面的内容
示例代码:
import java.io.*;
public class Test{
public static void main(String args[]){
Person p = new Person();
P.age(200);
}
}
class Person {
int age;
public void setAge(int age){
if(age<0||age>120){
Throw new MyAgeException(“年龄必须在0到120之间!”);
}
This.age = age;
}
}
class MyAgeException extends RuntimeException {
public MyAgeException (String msg){
super.(msg);
}
}
浙公网安备 33010602011771号