- Java的异常
- 捕获异常
- 抛出异常
- 自定义异常
Java的异常
Java异常是我们经常见到的在计算机程序运行的过程中,有一些异常是用户的错误输入。比如,希望用户输入一个int类型的数字,但是用户的输入是字符类型
// 假设用户输入了HelloWorld:
String str = "HelloWorld";
int num = Integer.parseInt(str); // NumberFormatException!
还有就是我们会看到FileNotFoundException! 这就是我们需要读取一个文件但是文件被用户给删除了!!!
还有很多情况 …
网络突然断了,连接不到远程服务器…
这就是需要我们的程序需要处理各种错误———异常!
捕获异常
捕获异常常用 try… catch 。把异常的代码放到try{},catch捕获对应得Exception及其子类。
public class DemoException{
public static void main(String [] args){
try{
String str = "HelloWorld";
int num = Integer.parseInt(str); //捕获异常信息
}catch (NumberFormatException e){
System.out.println(e); //打印异常信息 ;
}
}
}
我们也可以在外面写一个static去捕获这样一个异常:
public class DemoException{
public static void main(String [] args){
exce();
}
static void exce(){
try{
String str = "HelloWorld";
int num = Integer.parseInt(str); //捕获异常信息
}catch (NumberFormatException e){
System.out.println(e); //打印异常信息 ;
}
}
抛出异常
异常我们是可以手动抛出的
1.创建 Exception实力
2.用throws 抛出
void exce(String str) {
if (str==null) {
throw new NullPointerException();//下面的方法也可以
// NullPointerException e = new NullPointerException();
// throw e;
}
}
创建方法去抛出
public class exc {
public static void main(String[] args) {
try {
byte[] str= toGBK("安徽省的花");
System.out.println(Arrays.toString(str));
} catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
static byte[] toGBK(String s) throws UnsupportedEncodingException {
// 用指定编码转换String为byte[]:
return s.getBytes("GBK");
}
}
自定义异常
我们在抛出异常可以用Java标准库定义的函数
Exception
│
├─ RuntimeException
│ │
│ ├─ NullPointerException
│ │
│ ├─ IndexOutOfBoundsException
│ │
│ ├─ SecurityException
│ │
│ └─ IllegalArgumentException
│ │
│ └─ NumberFormatException
│
├─ IOException
│ │
│ ├─ UnsupportedCharsetException
│ │
│ ├─ FileNotFoundException
│ │
│ └─ SocketException
│
├─ ParseException
│
├─ GeneralSecurityException
│
├─ SQLException
│
└─ TimeoutException
如我们在一些输入不合理是去调用
static void age(int age){
if(age<=0){
throws new IllegalArgumentException (); //参数检测不合格
}
}
我们也可以自定义一些异常去健全我们的程序 ,异常也是一个Java类我们只要定义我么的异常去继承原有的异常类就好啦!
public class BaseException extends RunTimeException{
}