龙空技术网

Java checked、unchecked异常及throw、throws

小智雅汇 70

前言:

而今朋友们对“inputcheckedjquery”大致比较珍视,看官们都想要分析一些“inputcheckedjquery”的相关内容。那么小编在网上网罗了一些有关“inputcheckedjquery””的相关文章,希望大家能喜欢,咱们快快来学习一下吧!

将派生于Error或者RuntimeException的异常称为unchecked异常,所有其他的异常成为checked异常。

在Java中,异常主要分为两种类型:checked exceptions与unchecked exceptions。顾名思义,checked exceptions指的是被检查(受检查)的异常,unchecked exceptions指的是不被检查(不受检查)的异常。这里的检查指的是静态检查,即被编译器检查。

不受检查的异常不需要在方法或者是构造函数上声明,就算方法或者是构造函数的执行可能会抛出这样的异常,并且不受检查的异常可以传播到方法或者是构造函数的外面。相反,受检查的异常必须要用throws语句在方法或者是构造函数上声明(Use checked exceptions for recoverable conditions.)。

checked exceptions :需要在代码中显式地在方法签名中加上throws语句,或用throws-catch语句处理,否则编译不通过。

unchecked exceptions :不需要在代码中显式地处理,事实上是不鼓励显式的处理,因为这样的代码是多余的。

Exception CHECKED   1  IOException CHECKED    2 AWTException CHECKED    3 RunTimeException        3.1 ArithmeticException        3.2 llegalArgumentException            NumberFormatException        3.3 IndexOutOfBoundsException            ArrayIndexOutOfBoundsException        3.4 NoSuchElementException            InputMismatchException           3.5 Others    4 Others CHECKED

What are two ways your code can handle a checked exception?

Handle it in a catch{} block, orthrow it to the method's caller.

Input and output are especially error prone. Exception handling is essential for I/O programming.

输入和输出尤其容易出错。异常处理对于I/O编程至关重要。

An exception is a problem that occurs when a program is running. Often the problem is external to the program, such as bad user input, or mechanical failure of an I/O device. When an exception occurs, the Java virtual machine creates an object of class Exception which holds information about the problem.

异常是程序运行时发生的问题。问题通常是程序外部的,例如用户输入错误或输入/输出设备的机械故障。当异常发生时,Java虚拟机创建一个Exception类的对象,该对象保存有关问题的信息。

IOException is a checked exception. Some programs use the readLine() method of BufferedReader for input. This method throws an IOException when there is a problem reading. Programs that use BufferedReader for input need to do something about possible exceptions.

IOException是checked exception。有些程序使用BufferedReader的readLine()方法进行输入。当读取出现问题时,此方法引发IOException。使用BufferedReader进行输入的程序需要对可能的异常进行处理。

Scanner may also be connected to a disk file. Characters from the file are put into a stream one after another.

Scanner也可以连接到磁盘文件。文件中的字符一个接一个地放入流中。

For checked Exceptions, a method must either declare that it throws the Exception, or it must catch the Exception.

对于checked Exceptions,方法必须声明抛出异常,或者必须捕获异常。

Below program catches both Exception types that might arise. If both the creation of the Scanner and the execution of scan.nextInt() worked, then the square of the number is printed out and neither catch block is executed.

以下程序捕获可能出现的两种异常类型。如果同时创建Scanner和scan.nextInt(),然后输出数字的平方,并且不执行任何catch块。

import java.util.*;import java.io.*;public class EchoSquareException{    public static void main (String[] args)    {        int num, square;        Scanner scan = null;                try        {            File file = new File("myData.txt"); // create a File object            scan = new Scanner( file );      // connect a Scanner to the file            num = scan.nextInt();  // read and convert the first token            square = num * num ;            System.out.println("The square of " + num + " is " + square);        }        catch ( IOException iox )        {            System.out.println("Error opening the file");        }        catch ( InputMismatchException imx )        {            System.out.println("Bad data in the file");        }        if( scan != null ) scan.close();        System.out.println("Good-bye");    }}

关于异常的一些设计哲学:

① 异常本就应该是函数签名的一部分,就像函数的返回类型一样。

② Java 的异常并不全是 Checked Exception,RuntimeException 并不是 Checked。

③ 异常不应该被用来传递程序逻辑的 Bug,比如空指针解引用。

④ 在一个函数的调用处,并没有显式地说明某个函数调用是否会抛出异常。大部分情况下都是一个try 包住很多可能发生异常的函数调用,处理方式太过于粗粒度,也不利于 Code Review。

⑤ Java 并没有鼓励“单一失败模式”(即 throws Exception)。有些时候,多失败模式是有必要的,但多数情况下,程序的恢复处理逻辑与具体发生了什么错误无关(即只需要直知道成功与否即可)。当与具体发生的错误有关时,作者推荐使用 “The Keeper Pattern”。

⑥ 相比于 Checked Exception,Unchecked Exception 可靠性更低,它需要以文档的方式说明一个函数可能会抛出什么异常,对程序员、IDE、编译器都不友好。但正如 Andrew 在一篇采访 The Trouble with Checked Exceptions 中所说,在某些时候(比如应用开发),大多数人并不关心如何处理异常,他们只关心当异常发生时我要处理好后事(C# 的 using),剩下的事就交给最上层的 catch 去做好了。这是大家喜欢 Unchecked Exception 的原因。

throw and throws exception:

throw关键字用来在程序中明确地抛出异常,相反,throws语句用来表明方法不能处理的异常。每一个方法都必须要指定哪些异常不能处理,所以方法的调用者才能够确保处理可能发生的异常,多个异常是用逗号分隔的。

throw demo code:

try{    System.out.print("Enter the numerator: ");    num = scan.nextInt();    System.out.print("Enter the divisor  : ");    div = scan.nextInt();        if( div == 0 ) throw new ArithmeticException()            System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) );}catch (InputMismatchException ex ){    System.out.println("You entered bad data." );    System.out.println("Run the program again." );}catch (ArithmeticException ex ){    System.out.println("You can't divide " + num + " by " + div);}

throws demo code:

import java.util.* ;import java.io.* ;public class RateCalc{    public static int calcInsurance( int birthYear ) throws Exception    {        final int currentYear = 2000;        int age = currentYear - birthYear;                if( age < 16 )        {            throw new Exception("Age is: " + age );        }        else        {            int drivenYears = age - 16;            if( drivenYears < 4 )                return 1000;            else                return 600;        }    }        public static void main ( String[] a )    {        Scanner scan = new Scanner( System.in );        System.out.println("Enter birth year:");        int inData = scan.nextInt();                try        {            System.out.println( "Your insurance is: " + calcInsurance( inData ) );        }        catch ( Exception oops )        {            System.out.println( oops.getMessage() + " Too young for insurance!" );        }    }}

-End-

标签: #inputcheckedjquery