`

java_exception catch or throw

    博客分类:
  • Java
 
阅读更多

java exception catch or throw

via: http://blog.sina.com.cn/s/blog_75698d3701012b57.html

 

1、java异常机制

java中使用Throwable对象进行异常处理,Throwable是所有异常处理的父类,有两个子类:Error和Exception

Error一般为系统异常,已知子类AnnotationFormatError, AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, FactoryConfigurationError, IOError, LinkageError, ServiceConfigurationError, ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError ,可以看出是非常严重错误,很难进行捕获处理,程序员很难进行修复,几乎导致程序生命周期结束,所以一般程序不进行Error异常处理。

Exception是在程序运行期间发生的不正常事件,通过异常处理机制可以使程序正常运行,这些异常是程序员能够修复处理的。

Exception又分为 运行时异常 和 普通异常

运行时异常是RuntimeException类及子类范围的异常类

除了运行异常外的Exception子类为普通异常类

 

运行异常和普通异常区别通过以下例子可以看出:

public class Tools {

 public static void fun()throws ArithmeticException,NumberFormatException{//运行时异常

  int i,j,result;

  String in="0";

  i=10;

  j=Integer.parseInt(in);

  result=i/j;

  System.out.println(result);

 }

}

public static void main(String[] args){

  Tools.fun();

}

抛出的异常为运行时异常在调用时不需要捕获异常

 

public static void fun()throws ClassNotFoundException{//普通异常

  int i,j,result;

  String in="0";

  i=10;

  j=Integer.parseInt(in);

  result=i/j;

  System.out.println(result);

}

public static void main(String[] args){

  try {

      Tools.fun();

  } catch (ClassNotFoundException e) {

     e.printStackTrace();

  }

}

抛出的异常为普通异常时,调用方法时需要异常捕获。

两者都是在运行过程中出现的异常。

 

2、java处理异常方式

java异常处理采用抓抛模式完成

抓(try{}catch(){}finally{})

try中代码可能有异常出现的代码,出现异常时终止执行异常之后代码

catch是捕获出现的异常,出现异常时执行其中代码,catch中定义捕获异常类型

finally中代码任何情况下都执行                                                                                                

Exception是异常类型的基类

public static void main(String[] args){

  try{

   int arr[]={1,0,3};

   int result=arr[0]/arr[1];

   System.out.println(result);

  }catch(Exception e){

   System.out.println("异常!");

   e.printStackTrace();//异常描述

  }finally{

   System.out.println("最终执行!");

  }

}

 

抛(throw/throws)

throws是方法抛出异常,在声明方法时定义要抛出异常类型,告知方法的调用者本方法运行过程中可能出现什么异常,在调用时应进行异常监控。(抛出的异常大多为普通异常)

public static void fun()throws ClassNotFoundException{

  int i,j,result;

  String in="0";

  i=10;

  j=Integer.parseInt(in);

  result=i/j;

  System.out.println(result);

 }

public static void main(String...args){

  try {

   Tools.fun();

  } catch (ClassNotFoundException e) {

   e.printStackTrace();

  }

 }

throw是方法内代码块抛出异常实例

class myException extends Exception{

  String msg;

  myException(int age){

  msg="age can not be positive!";

  }

  public String toString(){

  return msg;

  }

}

 

class Age{

  public void intage(int n) throws myException{

  if(n<0||n>120){

  myException e=new myException(n);

  throw e; //是一个转向语句,抛出对象实例,停止执行后面的代码

  }

  if(n>=0){

  System.out.print("合理的年龄!");

  }

}

   

public static void main(String args[]) {

  int a=-5;

  try { //try catch 必需有

  Age age = new Age();

  age.intage(a);//触发异常

  System.out.print("抛出异常后的代码") ;//这段代码是不会被执行的,程序已经被转向

  } catch (myException ex) {

  System.out.print(ex.toString());

  }

  finally{//无论抛不抛异常,无论catch语句的异常类型是否与所抛出的例外的类型一致,finally所指定的代码都要被执行,它提供了统一的出口。

  System.out.print("进入finally! ");

  }

  }

}

 

结果:年龄非法! 进入finally!

 

拓展

4.常见的运行时异常

ArithmaticExceptionDemo.java

public class ArithmaticExceptionDemo {   

    //计算两个数相除的结果   

    public int divide(int a,int b){

            return a/b;

    }

    

    //抛出异常

    //Exception in thread "main" java.lang.ArithmeticException: / by zero   

    public static void main(String args[]){

            ArithmaticExceptionDemo excp = new ArithmaticExceptionDemo();

            excp.divide(10,0);

    }   

}

 

ArrayStoreExceptionDemo.java

public class ArrayStoreExceptionDemo {

    //程序的入口

    public static void main(String arsg[]){

            //Object类型 字符串数组

            Object x[] = new String[3];

            

            //为了不让程序在编译时就检查报错 就故意写成上述类型

            //如果写成 下面类型就会直接报错

            //String x [] = new String[3];

            

            try{

                //错误的类型 java.lang.ArrayStoreException: java.lang.Integer

                 x[0] = new Integer(0);

            }catch(ArrayStoreException ae){

                    System.err.println(ae.toString()+"ok");

                    ae.printStackTrace();

            }

            System.out.println("程序正常运行!");

    }

}

 

ClassCastExceptionDemo.java  

public class ClassCastExceptionDemo {   

       

    public static void main(String args[]){   

               

            Object x = new Integer(12);   

           

            try{   

                System.out.println((String)x);   

            }catch(ClassCastException ce){   

                    System.err.println(ce.toString());   

                }   

    }   

  

}  

 

 

EmptyStackExceptionDemo.java

import java.util.EmptyStackException;

import java.util.Stack;

public class EmptyStackExceptionDemo {

    public static void main(String args[]){

        Stack<String> s = new Stack<String>(); //栈

        s.push("a");    //先压入 a      压栈 push()方法

        s.push("b");    //    b 

        s.push("c");    // 最后压入 c   

        

        try{

            while(s.size()>0){

                System.out.println( s.pop());    //依次循环将栈中的元素弹出 pop()方法

            }

            s.pop(); // 此动作将造成异常,因为栈中所有元素在上面的 循环中就已经弹出,为空栈

        }catch(EmptyStackException ee){

                System.err.println(ee.toString());

                ee.printStackTrace();

            }

    }

}

 

 

IndexOutOfBoundsExceptionDemo.java

public class IndexOutOfBoundsExceptionDemo {

    public static void main(String args[]){

            int num [] = new int[10];

            try{

                //数组10个长度   12次循环就报错

                for(int i=0;i<12;i++){

                    System.out.println(num[i]); //循环超出范围

                }

            }catch(IndexOutOfBoundsException ie){

                    System.err.println(ie.toString());

                    ie.printStackTrace();

                    System.out.println( ie.getCause());

                    System.err.println(ie.getMessage());

                }   

            System.out.println("程序还 能继续执行");

        }

}

 

 

NegativeArraySizeExceptionDemo.java

public class NegativeArraySizeExceptionDemo {

    public static void main(String args[]){

            try{

                int num [] = new int [-9];   //创建大小为负的数组,则抛出该异常

                System.out.println(num[0]);

            }catch(NegativeArraySizeException ne){

                System.err.println(ne.toString()); //err红色打印

                ne.printStackTrace();

            }

        }

}

 

 

NullPointerExceptionDemo.java

public class NullPointerExceptionDemo {

    String nameString;  //类字符串成员变量  默认为null

    public static void main(String args[]){

            try{

                //返回字符串第一个字符 但将出现异常 相当于 null.charAt(0);

                char c = new NullPointerExceptionDemo().nameString.charAt(0);

                System.out.println(c);

            }catch(NullPointerException ne){

                System.err.println(ne.toString());

                ne.printStackTrace();

            }

        }

}

 

 

NumberFormatExceptionDemo.java

public class NumberFormatExceptionDemo {

    public static void main(String args[]){

            String a = "3";

            int b = (int)new Integer(a);

            System.out.println(b);//这个是没有问题的

            try{

                String c = "aa";

                //java.lang.NumberFormatException: For input string: "aa"

                int d = (int)new Integer(c);

                System.out.println(d);//这个是有问题的

            }catch(NumberFormatException ne){

                System.err.println(ne.toString());

                ne.printStackTrace();

            }

        }

}

分享到:
评论

相关推荐

    File_实用案例_实现文件拷贝_FileCopy.java

    /* ... All rights reserved. ... /** A convenience method to throw an exception */ private static void abort(String msg) throws IOException { throw new IOException("FileCopy: " + msg); } }

    Java反射封装库joor.zip

    or maybe just wrap in your preferred runtime exception: throw new RuntimeException(e);} jOOR写法:   Employee[] employees = on(department).call("getEmployees").get();for (Employee employee : ...

    Java 语言基础 —— 非常符合中国人习惯的Java基础教程手册

    在 java 语言中,Java 程序的基本单位是类,也就是说:一个 Java 程序是由多个类组成 的。定义一个类与定义一个数据类型是有区别的。在程序设计语言中,把定义数据类型的能 力作为一种很重要的能力来对待。在面向...

    JSP Simple Examples

    In try block we write those code which can throw exception while code execution and when the exception is thrown it is caught inside the catch block. Multiple try catch We can have more than one try/...

    android 串口驱动

    } catch (Exception e) { e.printStackTrace(); throw new SecurityException(); } } mFd = open(device.getAbsolutePath(), baudrate); if (mFd == null) { Log.e(TAG, "native open ...

    带注释的Bootstrap.java

    import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; ...

    整理后java开发全套达内学习笔记(含练习)

    }catch(Exception e){} }} 数值保存方式: 正数= 二进制 负数= 补码 补码= 反码 +1 正数=负数的补码(反码+1) 反码= 非(二进制数) 八进制数,零开头 011(八进制)=9(十进制) 十六进制数,零x开头 0x55...

    Java 数据库主键生成类 IdWorker

    } catch (Exception e) { e.printStackTrace(); } } this.lastTimestamp = timestamp; long nextId = ((timestamp - twepoch )) | (this.workerId ) | (this.sequence); System.out.println("timestamp:" + ...

    Servlet查询数据库案例--Query(java源码)

    // If anything goes wrong, log it, wrap the exception and re-throw it try { Class.forName(driverClassName); db = DriverManager.getConnection(url, username, password); } catch (Exception e) { ...

    Java邮件开发Fundamentals of the JavaMail API

    addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard Edition (J2SE) 1.2.x or 1.3.x. A general familiarity with object-oriented programming ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare ...

    springmybatis

    }catch(Exception e){ e.printStackTrace(); } } public static SqlSessionFactory getSession(){ return sqlSessionFactory; } public static void main(String[] args) { SqlSession session = ...

Global site tag (gtag.js) - Google Analytics