java-异常

                    Throwable
                           / \
                          /   \
                         /     \
                        /       \
                    Error     Exception
                                 /       \
                                /          \
                               /             \
                              /                \
                    非运行时异常            RuntimeException

Error(系统错误,例如虚拟机错误,我们处理不了,所以不用去处理)

Exception:

              1.RuntimeException(经常出现,可处理可不处理,unchecked(不需要在代码中显式地捕获异常做处理),每次处理会影响性能,比如空指针异常,javac不会出错,java命令之后运行期间才会出错

              2.非运行时异常(必须处理,checked(需要显式即捕获或者抛出),不然编译时就出错,就是javac命令时就出错,对应我们在集成环境例如eclipse保存时出错)

自定义异常:一般是继承Exception,先catch小的异常,再catch大的异常

这里讲的异常是运行过程中的异常:不是javac命令出现的异常,而是java命令出现的异常

Java通过面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口。在Java中,每个异常都是一个对象,它是Throwable 类或其它子类的实例。当一个方法出现异常后便抛出一个异常对象,该对象中包含有异常信息,调用这个对象的方法可以捕获到这个异常并进行处理。Java的异 常处理是通过5个关键词来实现的:try、catch、throw、throws和finally。一般情况下是用try来执行一段程序,如果出现异常, 系统会抛出一个异常,这时候你可以通过它的类型来捕捉(catch)它,或最后(finally)由缺省处理器来处理。

规定:重写方法需要抛出与原方法所抛出异常类型一致的异常或不抛出异常
用try来指定一块预防所有"异常"的程序。紧跟在try程序后面,应包含一个catch子句来指定你想要捕捉的"异常"的类型。
throw语句用来明确地抛出一个"异常"。(抛出异常时,RuntimeException类型的异常不需try catch或声明,其他类型的Exception需要)
throws用来申明一个成员函数可能抛出的各种"异常"。(某方法申明了异常,其他的方法调用它,必须做异常处理)
Finally为确保一段代码不管发生什么"异常"都被执行一段代码。

1.throws关键字通常被应用在声明方法时,使用它主要是API中写明了哪些方法可能抛出了哪些异常,我们就用它来指定抛出一些已知可能的异常,如果不确定该方法有哪些异常该抛出时,我们就使用下面这个关键字,并且在方法后声明该异常。多个异常可以使用逗号隔开。当在主函数中调用该方法时,如果发生异常,就会将异常抛给指定异常对象

2.throw关键字通常用在方法体中,并且抛出一个异常对象。程序在执行到throw语句时立即停止,它后面的语句都不执行
通过throw抛出异常后,如果想在上一级代码中来捕获并处理异常,则需要在抛出异常的方法中使用throws关键字在方法声明中指明要跑出的异常;
如果要捕捉throw抛出的异常,则必须使用try—catch语句

测试运行时异常的处理方法:

View Code
package TestException;

/** 
 * @Package TestException

 * @ClassName: TestRuntimeException

 * @Description: TODO(运行时异常的抛出异常方式和catch异常

 * @author andy

 * @date 2013-3-11 下午03:57:01

 */
public class TestRuntimeException {
    //抛出异常第一种方法
    /*public void a(int i) throws ArithmeticException{
            int a = 3/i;
    }*/
    
    //抛出异常第二中方法
    public void a(int i){
        try {
            int a = 3/i;
        } catch (ArithmeticException e) {
            throw e;
        }
    }
    
    public static void main(String[] args){
        // TODO Auto-generated method stub
        TestRuntimeException te = new TestRuntimeException();
        try {
            te.a(0);
        } catch (Exception e) {
            System.out.println("main方法调用a方法catch到了运行时异常");
        }
    }
}

测试非运行时异常的处理方法:

View Code
package TestException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

/** 
 * @Package TestException

 * @ClassName: TestNoRuntimeException

 * @Description: TODO(非运行时异常抛出异常和catch异常的方式)

 * @author andy

 * @date 2013-3-11 下午04:06:27

 */
public class TestNotRuntimeException {
    
    //抛出异常第一种方式
    public void a() throws FileNotFoundException {
        try {
            FileInputStream in = new FileInputStream("txt");
        } catch (FileNotFoundException e) {
            throw e;
        }
    }
    
    //抛出异常第二种方式
    /*public void a() throws FileNotFoundException {
            FileInputStream in = new FileInputStream("txt");

    }*/
    
    public static void main(String[] args){
        // TODO Auto-generated method stub
        TestNotRuntimeException te = new TestNotRuntimeException();
        try {
            te.a();
        } catch (Exception e) {
            System.out.println("main方法调用a方法catch到了非运行时异常");
        }
    }
}

 

想要被调用的上一级捕获到异常做异常处理,有以下几种方式

总结,两种异常在抛出异常时的不同方式(被调用方)

运行时异常,没有要求

runtimeexception

1.throws

public void a(int i) throws ArithmeticException{
        //try {
            int a = 3/i;
        //} catch (ArithmeticException e) {
            
        //}
    }
View Code

2.throw + try catch (+ throws 非必须)

public void a(int i) throws ArithmeticException {
        try {
            int a = 3 / i;
        } catch (ArithmeticException e) {
            throw e;
        }
    }
View Code
public void a(int i)  {
        try {
            int a = 3 / i;
        } catch (ArithmeticException e) {
            throw e;
        }
    }
View Code

3.throw

public void a(int i)  {
        int a = 3 / i;
        if(1==1){
            throw new ArithmeticException();
        }else{
            System.out.println("正常");
        }
    }
View Code

 4.不做任务处理也可以

public void a(int i)  {
        int a = 3 / i;
        System.out.println("发生异常这里的代码不再执行了");
        /*if(1==1){
            throw new ArithmeticException();
        }else{
            System.out.println("正常");
        }*/
    }
View Code

 

非runtimeexception

非运行时异常,要么声明(即throws),要么抛出(即throw,非运行时异常throw时,同时必须throws)

1.throws

public void b() throws FileNotFoundException{
        //try {
            FileInputStream in = new FileInputStream("txt");
        //} catch (FileNotFoundException e) {
                //throw e;
        //}
    }
View Code

2.throw + try catch +throws  

public void b() throws FileNotFoundException{
        try {
            FileInputStream in = new FileInputStream("txt");
        } catch (FileNotFoundException e) {
                //throw e;
        }
    }
View Code

3.throw + throws

public void b() throws FileNotFoundException{
        if(1==1){
            throw new FileNotFoundException();
        }else{
            System.out.println("正常");
        }
    }
View Code

 

解决异常(调用方) : try catch

public static void main(String[] args){
        // TODO Auto-generated method stub
        TestException te = new TestException();
        try {
            //te.a(2);
            te.b();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("catch到了异常");
            e.printStackTrace();
        }
    }
View Code

 

 

 整理哪些代码之后的代码不会再执行:

public void a(int i) {
        if(i == 0)
            throw new ArithmeticException("被除数为0");
        System.out.println("throw之后这里的代码不再执行了");
    }
    public void aa(int i) {
        int a = 3 / i;//运行时异常
        System.out.println("发生异常后这里的代码不再执行了");
    }
    public void aaa(int i) throws FileNotFoundException {
        FileInputStream in = new FileInputStream("txt");//非运行时异常
        System.out.println("发生异常后这里的代码不再执行了");
    }
View Code

 进而容易整理出哪些代码之后的没有返回值:try catch之后,调用它的方法就能得到返回值

package TestException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class TestNotReturn {

    public static void main(String[] args){
        // TODO Auto-generated method stub
        TestNotReturn te = new TestNotReturn();
        try {
            //System.out.println(te.a(0));;
            //System.out.println(te.aa(0)); ;
            //System.out.println(te.aaa(0));;
            //System.out.println(te.bb(0));;
            //System.out.println(te.bbb(0));;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("catch到了异常");
            e.printStackTrace();
        }
    }
    public String a(int i) {
        if(i == 0){
            try {
                throw new ArithmeticException("被除数为0");//运行时异常
            } catch (Exception e) {
                e.printStackTrace();
                return "here is can  return a";
            }
            
        }
        System.out.println("throw之后这里的代码不再执行了");
        return "a";
    }
    public String aa(int i) {
        try {
            int a = 3 / i;//运行时异常
        } catch (Exception e) {
            e.printStackTrace();
            return "here is can  return aa";
        }
        System.out.println("发生异常后这里的代码不再执行了");
        return "aa";
    }
    public String aaa(int i) {
        try {
            FileInputStream in = new FileInputStream("txt");//非运行时异常
        } catch (Exception e) {
            e.printStackTrace();
            return "here is can  return aaa";
        }
        System.out.println("发生异常后这里的代码不再执行了");
        return "aaa";
    }
    
    //对应上面的aa方法
    public String bb(int i) {
        int a = 3 / i;//运行时异常
        return "here is can  return aa";
    }
    
    //对应上面的aaa方法
    public String bbb(int i) throws FileNotFoundException {
        FileInputStream in = new FileInputStream("txt");//非运行时异常
        return "here is can  return aaa";
    }
    
}
View Code

 

 

自定义异常:

View Code
 1 class MyException2 extends Exception { //创建自定义异常类
 2      String message; 
 3      
 4      public MyException2(String ErrorMessagr) { 
 5            message = ErrorMessagr;
 6      }
 7      
 8      public String getMessage(){ 
 9       return message;
10      }
11      
12     }
13 
14 public class Captor { 
15     
16     static int quotient(int x,int y) throws MyException2 {//定义方法抛出异常
17         if(y < 0){ 
18             throw new MyException2("除数不能是负数");//异常信息
19         }
20         return x/y;
21     }
22     
23     public static void main(String args[]){ 
24         try{ 
25             int result = quotient(3,-1);
26         }catch (MyException2 e) { 
27             System.out.println(e.getMessage()); 
28         }
29         catch (ArithmeticException e) {
30 
31             System.out.println("除数不能为0");
32         }
33         catch (Exception e) { 
34             System.out.println("程序发生了其他的异常");
35         }
36     }
37 }

 

 多线程捕获异常:

ExecutorService pool= Executors.newFixedThreadPool(20);
List<Future<?>>  futures =new ArrayList<Future<?>>();

futures.add(pool.submit(handle));
while(futures.size()>0){ Iterator<Future<?>> iterator = futures.iterator();
Future future = null; while(iterator.hasNext()){future =iterator.next(); future.get(); if(future.isDone()){ result_table_number++; iterator.remove(); } }

 

 

pool= Executors.newFixedThreadPool(tableEnNames.size(), new HanlderThreadFactory());
            futures =new ArrayList<Future<?>>();
            for(String tableEnName:tableEnNames){
                CacheTable cacheTable = cache.getCacheTableByTableName(tableEnName);
                if(null == cacheTable){
                    return;
                }
                //全文检索      模糊检索
                List<I_TableProcess> tableProcesses = null;
                SingleTableHandle handle = null;
                if(0 == searchType){
                    //System.out.println("searchType:"+searchType+",tableEnName:"+tableEnName+",searchKeyword:" +searchKeyword );
                    //tableProcesses = doretrieval(searchType,tableEnName,cacheTable,searchKeyword,"union",MatchMode.模糊);
                    handle = new SingleTableHandle(searchType, tableEnName, cacheTable, searchKeyword, "union", MatchMode.模糊, uv, ip, new DBUtils_JiZhen(), request_id);
                //身份证号码 精确检索
                }else{
                    //System.out.println("searchType1:"+searchType+",tableEnName:"+tableEnName+",searchKeyword:" +searchKeyword );
                    handle = new SingleTableHandle(searchType, tableEnName, cacheTable, searchKeyword, "xmsfzh", MatchMode.精确, uv, ip, new DBUtils_JiZhen(), request_id);
                    //tableProcesses = doretrieval(searchType,tableEnName,cacheTable,searchKeyword,"xmsfzh",MatchMode.精确);
                }
                futures.add(pool.submit(handle));
                /*if(null != tableProcesses
                        && tableProcesses.size()>=1
                        && null != tableProcesses.get(0)
                        && null != tableProcesses.get(0).getDocs()
                        && 0 == tableProcesses.get(0).getDocs().size()){
                    //return;
                }
                if(null == tableProcesses
                        || 0 == tableProcesses.size()
                        || null == tableProcesses.get(0).getDocs()
                        || 0 == tableProcesses.get(0).getDocs().size()){
                    log.info("gz_search_request表中主键ID为# " + request_id +"#检索出现错误,索引连接异常!");
                    saveFlag = 9;
                    return;
                }*/
                //String search_result = allXmlHead + packagePartXML(tableEnName,tableProcesses,cacheTable) + allXmlTail;
                //System.out.println("search_result:"+search_result );    
                //saveData(tableEnName,tableProcesses.get(0).getTotalHits(),search_result);
            }
            
            while(futures.size()>0){
                Iterator<Future<?>> iterator = futures.iterator();
                while(iterator.hasNext()){
                    System.out.println("kkkk");
                    Future future =iterator.next();
                    future.get();
                    if(future.isDone()){
                        result_table_number++;
                        iterator.next().get();
                        iterator.remove();
                    }
                }

posted on 2012-04-09 11:15  lovebeauty  阅读(682)  评论(0编辑  收藏  举报

导航