简体   繁体   English

学习Try-Catch

[英]Learning Try-Catch

I'm a Java beginner so please bear with me 我是Java初学者,所以请耐心等待

static int load = 100;
static int greet;

public void loadDeduct(int cLoad, int c){
    int balance;
    balance = cLoad - 7;
    System.out.println("Your balance: " + balance);
}

public void loadDeduct(int tLoad){
    int balance;
    balance = tLoad - 1;
    System.out.println("Your balance is: " + balance);
}

public static void main (String [] args){
    int choice;
    Scanner scan = new Scanner(System.in);

    System.out.println("I'm a cellphone, what do you want to do?");
    System.out.println("Press 1 to send SMS / Press 2 to Call");

    choice = scan.nextInt();

    CellphoneLoad N95 = new CellphoneLoad();

    if (choice == 1){
        N95.loadDeduct(load);
    }else if (choice == 2){
        N95.loadDeduct(load, greet);
    }else{
        System.out.println("Invalid Option!!!");
    }

How do I implement the exception handling with this program? 如何使用此程序实现异常处理? I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. 我不太确定如何使用catch块,因为我们还没有教过关于整个异常的事情。 It was just an exercise we were asked to do. 这只是我们被要求做的一项运动。 I want to replace the if else statements with a try-catch blocks... is that possible? 我想用try-catch块替换if else语句......这可能吗?

One important principle to consider with exceptions in Java is that there are two types: 1. Runtime 2. Typed/explicit (for lack of a better word) 在Java中考虑异常的一个重要原则是有两种类型:1。运行时2.类型/显式(缺少更好的单词)

Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error. 当出现编程错误时,应该抛出运行时异常,并且通常不应该捕获它们,除非您在顶层捕获报告错误。

Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them. 类型/显式异常在方法调用上进行修饰,并且应该在那里,以便调用者可以对它们采取某些操作。

In the case of the code above, there isn't really a place that feels like it should use exception handling. 在上面的代码的情况下,没有一个地方感觉它应该使用异常处理。

And as Patrick pointed out, you don't generally want to use exceptions for flow control. 正如Patrick指出的那样,您通常不希望使用流量控制的异常。

It is not ideal to use Exceptions for flow control. 使用Exceptions进行流量控制并不理想。 From your code it is not clear what Exceptions might be thrown. 从您的代码中不清楚可能会抛出什么异常。 Maybe you can elaborate a bit more. 也许你可以再详细说明一下。

The only part of your code that might possibly throw an exception is the call to: 代码中唯一可能引发异常的部分是调用:

scan.nextInt();

According to the JavaDocs, this can throw the following possible exceptions: 根据JavaDocs,这可能会引发以下可能的异常:

  • InputMismatchException (if the next token does not match the Integer regular expression, or is out of range) InputMismatchException(如果下一个标记与Integer正则表达式不匹配,或者超出范围)
  • NoSuchElementException (if input is exhausted) NoSuchElementException(如果输入已用尽)
  • IllegalStateException (if this scanner is closed) IllegalStateException(如果此扫描程序已关闭)

So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so: 因此,如果您希望您的代码考虑到抛出这些异常的可能性,您应该像这样重写它:

try {
    choice = scan.nextInt();
} 
catch (InputMismatchException e) {
  System.out.println(e.getMessage());
}
catch (NoSuchElementException e) {
  System.out.println(e.getMessage());
}
catch (IllegalStateException e) {
  System.out.println(e.getMessage());
}

Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature. 一般来说,你希望你的“捕获”块开始具体或很可能发生在不太可能/更一般的性质。

You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime). 你可以另外“抛出”异常,以便异常发生的任何方法都不处理它 - 调用异常导致方法的方法必须处理它(或者再次抛出异常等,直到它到达Java运行时)。

In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement: 如果您希望替换“if”语句,我建议使用“switch”语句:

switch (choice) {
    case 1:  N95.loadDeduct(load);
             break;
    case 2:  N95.loadDeduct(load, greet);
             break;
    default: System.out.println("Invalid Option!!!");
}

The Scanner.nextInt() method can throw a few exceptions. Scanner.nextInt()方法可以抛出一些例外。 The linked page of the API Specifications lists out the three exceptions which can be thrown. API规范的链接页面列出了可以抛出的三个例外。

For example, if a non-integer value is entered, such as "one" instead of 1 , an InputMismatchException can be thrown. 例如,如果输入非整数值,例如"one"而不是1 ,则可以抛出InputMismatchException

In general, a try-catch is used to catch exceptions, as illustrated in the following code: 通常, try-catch用于捕获异常,如以下代码所示:

try
{
    Integer.parseInt("one");      // Statement that can cause an exception.
}
catch (NumberFormatException e)   // Specify which exception to catch.
{
    // Code to handle the NumberFormatException.
}

More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials . 有关异常的更多信息,请参阅课程: Java教程的 例外 In particular, the Catching and Handling Exceptions section may be useful. 特别是, 捕获和处理异常部分可能很有用。

Adding exceptions in this piece of code does not add much value. 在这段代码中添加异常并没有增加太多价值。 What I can think of is something like this: 我能想到的是这样的:

public static void main (String [] args){

.....

try{
 handleUserChoice(choice);//new method
}
catch(InvalidChoiceException e){
 System.out.println("Invalid Option!!!");
}
}

It's really pretty simple. 这真的很简单。 First identify where you want an exceptioon. 首先确定你想要的地方。 There can be exceptinos thrown by library code or you can throw your own. 可以通过库代码抛出除外,也可以自己抛出。 Then use a try .. catch to handle it. 然后使用try .. catch来处理它。 Here's a simple "hello, world" ish example: 这是一个简单的“你好,世界”的例子:

public class TryTry {

    public void doIt() throws Exception {
       System.err.println("In the doIt method.");
       throw new Exception("Hello there!");
    }

    public static void main(String[] argv){
       TryTry t = new TryTry();
       // here we'll catch it.
       try {
           System.err.println("About to call doIt().");
          t.doIt();
       } catch (Exception e) {  // e now has your exception object
          System.err.println("In the exception handler.");
          System.err.println("Exception says: "+ e);
       }
    }
}

The effect of throw is to construct that exception object and send it up the stack until it's caught. throw的作用是构造该异常对象并将其发送到堆栈直到它被捕获。 To catch it, you surround the code that might throw it with tr { ... } , and handle the exception with catch . 为了捕获它,你可以使用tr { ... }包围可能抛出它的代码,并使用catch处理异常。

Here's the results: 结果如下:

javac TryTry.java && java TryTry
About to call doIt().
In the doIt method.
In the exception handler.
Exception says: java.lang.Exception: Hello there!

I don't see any reason to use exceptions instead of the if-else block. 我没有看到任何使用异常而不是if-else块的理由。 you could try using a switch statement, it'd look better. 你可以尝试使用switch语句,它看起来更好。

you should use exceptions to handle errors that might occur inside the methods loadDeduct. 您应该使用异常来处理方法loadDeduct中可能发生的错误。 then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong. 然后你会用一个try-catch块来包围调用N95.loadDeduct的行,写下如果loadDeduct出错会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM