目录java
public static void main(String[] args) { // try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a / b; System.out.println("输入的两个数相除结果为: " + c); } //IndexOutOfBoundsException catch(IndexOutOfBoundsException ie){ System.out.println("数组越界"); } //NumberFormatException catch(NumberFormatException ne){ System.out.println("数字格式异常"); } //ArithmeticException catch(ArithmeticException ae){ System.out.println("算术异常"); } catch (Exception e) { System.out.println("未知异常"); } }
Java7后提供一个catch捕获多个异常
数组
public static void main(String[] args) { // try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a / b; System.out.println("输入的两个数相除结果为: " + c); } //Multiple Exception catch(IndexOutOfBoundsException | NumberFormatException | ArithmeticException me){ System.out.println("多个异常"); } catch (Exception e) { System.out.println("未知异常"); } }
public static void main(String[] args) { // try { FileInputStream i = new FileInputStream("a.txt"); } //Multiple Exception catch(IOException ie){ System.out.println("exception message: " + ie.getMessage()); ie.printStackTrace(); } catch (Exception e) { System.out.println("未知异常"); } }
exception message: a.txt (系统找不到指定的文件。) java.io.FileNotFoundException: a.txt (系统找不到指定的文件。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at com.company.project.exception.ExceptionPrint.main(ExceptionPrint.java:11)
package com.company.project.exception; import java.io.FileInputStream; import java.io.IOException; public class ExceptionPrint { public static void main(String[] args)throws IOException {//这里抛出IOException //throw exception FileInputStream i = new FileInputStream("a.txt"); } //定义的新函数抛出指定的异常 public static void test() throws Exception {}; }
throw和throws区别:jvm
public class ExceptionPrint { /*throws & throw*/ public static void main(String[] args)throws IOException {//这里抛出IOException FileInputStream i = new FileInputStream("a.txt"); } //定义的新函数抛出指定的异常 public static void test() throws Exception {}; public void DoSomething(){ int a = 1; int b = 2; if (a != b) { //能够定义本身的异常 throwMyException(); //也能够定义其余的异常,根据须要使用 throw new IndexOutOfBoundsException(); } } public static void throwMyException(){ System.out.println("我本身定义的异常"); } }
package com.company.project.exception; //MyNewException。java public class MyNewException extends Exception { //无参构造 public MyNewException(){}; //有参构造 public MyNewException(String msg){ super(msg); } }
finnaly在有try语句块的时候才能使用,在jvm不退出的状况下必定会执行函数