//java异常
/*
1,了解java 中的异常处理机制,有三种操作
a,声明异常
b,抛出异常
c,捕获异常
2,学会使用try-catch-finally来处理异常
3,学会如何声明异常和抛出异常
4,学会创建自己的异常
*/
//2,学会使用try-catch-finally来处理异常
/*使用try-catch
*/
public class TryCatchTest {
public static void main(String[] args) {
int number,value;
try{
number = 0;
value = 3/number;
//可能会抛出ArithmeticException异常,使用catch老捕获这个异常
}catch(ArithmeticException e){
e.printStackTrace();
System.out.println("错误:被0整除");
}
}
}
/*
定义一个try-catch-finally来捕获异常
*/
public class finallyTest {
public static void main(String[] args) {
try{
int[] a = new int[3];
a[3] =3;//数组超越边界
}catch(ArithmeticException e){
//Exception类是从Throwable继承的,同时也有其方法
//toString();对当前异常对象的描述
//getMessage();获取返回的信息
//printStackTrace();打印当前异常对象详细消息的字符串
System.out.println(" e.toString()"+ e.toString());
System.out.println("e.getMessage()"+ e.getMessage());
System.out.println ("e.hashCode()"+e.hashCode());
System.out.println ("e.printStackTrace()");
e.printStackTrace();
System.out.println("发生了异常!");
}finally{
//不管前面是否执行finally都会输出
System.out.println("最后执行这句话!");
}
}
}
//3,学会如何声明异常和抛出异常
/*会用关键字throw是在try中来声明,关键字throws是在方法体中声明
如果一个方法可能产生异常,那么该方法要么需要try-catch来捕获
并处理他们,要么主动声明抛出,否则该程序将无法编译,除非是编译
过成中的异常
throws关键字用在方法声明中
throw用在try块中来声明并抛出一个异常
public void go(){
try{
thorw new IOException("文件不存在!");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
import java.io.*;
public class throwsTest {
public static void main(String[] args){
throwsTest thorwstest = new throwsTest();
try{
thorwstest.readFile();
}catch(IOException e){
e.printStackTrace();
}
}
//readFile() 方法抛出IOException
public void readFile() throws IOException{
FileInputStream fis = new FileInputStream("hello.txt");
int b;
b = fis.read();
while(b!=-1){
System.out.println((char)b);
b = fis.read();
}
fis.close();
}
}
*/
/*运行结果,如果没有hello.txt就出现下面的 ,如果有就输入字符
* java.io.FileNotFoundException: hello.txt (系统找不到指定的文件。)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java面向对象设计.throwsTest.readFile(throwsTest.java:33)
at java面向对象设计.throwsTest.main(throwsTest.java:23)
*/
//4,学会创建自己的异常
//下面的代码中定义了声明了一个异常,并捕获,
public class TryCatchTest {
public static void main(String[] args) {
int number,value;
try{
number = 0;
value = 3/number;
}catch(Exception e){
e.printStackTrace();
System.out.println("错误:被0整除");
}
}
}