简体   繁体   English

尝试使用Java中的Catch Block

[英]Try Catch Block in Java

So I'm given this code and I have to create an Exception and then use a Try/Catch Block to catch it. 所以我给了这个代码,我必须创建一个Exception,然后使用Try/Catch Block来捕获它。 I've already made the Exception, at the bottom of the code. 我已经在代码的底部制作了Exception。 But I've never used a Try/Catch Block before and am not sure how to implement it. 但我以前从未使用过Try/Catch Block,也不确定如何实现它。

The Exception is if a rank that isn't listed under the enum is entered. 例外情况是输入未在enum下列出的等级。 I need to use a toString with the caught exception as well, but I'm pretty sure I can figure that one out. 我也需要使用带有捕获异常的toString ,但我很确定我可以解决这个问题。

package pracapp4;

import java.util.Scanner;

public class Staff extends Employee
{

  enum Title
  {
    DEPARTMENT_HEAD, DIRECTOR, DEAN, VICE_CHANCELLOR, CHANCELLOR
  }

  private Title title;

  public Staff()
  {
    super();
    title = Title.DEPARTMENT_HEAD;
  }

  public Staff(String firstName, String lastName, int salary, Title title)
  {
    super(firstName, lastName, salary);
    this.title = title;

  }

  @Override
  public String toString()
  {
    return super.toString() + "\n\tTitle: " + title;
  }


  @Override
  public void display()
  {

    System.out.println("<<Staff>>" + this);

  }

  @Override
  public void input(Scanner in)
  {
    super.input(in);

    if (in.hasNext())
    {
      this.title = Enum.valueOf(Title.class, in.next());
    }
  }

  class InvalidRankException extends Exception
  {
      public InvalidRankException()
      {
       super ("Unknown Rank Name: ");

      }   
  }
}

You don't need that exception. 你不需要那个例外。 The moment you add your Title enum as the type you pass into the Staff constructor it's impossible to provide a value that's not in the enum. 当你将Title枚举添加为传递给Staff构造函数的类型时,就不可能提供不在枚举中的值。 You'll never get an invalid title. 你永远不会得到无效的头衔。 That's the whole point of enum. 这就是枚举的全部要点。

UPDATE: A little code review is an order here. 更新:一个小代码审查是这里的一个订单。

  1. Your default constructor is rather odd. 你的默认构造函数相当奇怪。 You can be department head without a name or salary? 你可以成为没有名字或工资的部门负责人吗? A call to "this" is appropriate here, and better default values are in order. 这里调用“this”是合适的,并且更好的默认值是有序的。
  2. Whole numbers only for salary - OK. 整数只用于薪水 - 好的。 No units? 没单位? USD? 美元? Euro? 欧元?
  3. Can salary be negative? 薪水可以是负数吗? Does that make sense? 那有意义吗? (Note to self: Don't work there.) (自我注意:不要在那里工作。)
  4. Why do you need both toString and display? 为什么你需要toString和display? What is display overriding? 什么是显示覆盖? I'd recommend ditching display and sticking with toString. 我建议放弃显示并坚持使用toString。
  5. Your input method makes no sense whatsoever. 你的输入法没有任何意义。
  6. Why is that Exception an inner class? 为什么Exception是内部类?

try/catch are used to catch exceptions thrown by methods inside the try clause. try / catch用于捕获try子句中方法抛出的异常。 If the methods inside the try does not throw any exceptions then the try/catch will not makes sense. 如果try中的方法没有抛出任何异常,那么try / catch就没有意义了。 Right now you made your exception but there is no method that throws your exception. 现在你做了你的异常,但是没有抛出你的异常的方法。

This is simple example on how to use exceptions: 这是关于如何使用异常的简单示例:



public class myTest
{

  public void myMethod() throws InvalidRankException
  {
     //Logic here
    if(something_is_wrong)
    {
        throw new InvalidRankException("Invalid Rank on myMethod due ...");
    } 

}

  class InvalidRankException extends Exception
  {
      public InvalidRankException()
      {
       super ("Unknown Rank Name: ");

      }   
  }

Now, whenever you run MyTest.myMethod() the compiler will require a try/catch surrounding that call. 现在,无论何时运行MyTest.myMethod(),编译器都需要围绕该调用的try / catch。


    MyTest test = new MyTest();
    try
    {
       test.myMethod();
    }
    catch(InvalidRankException ex)
    {
       //Something went wrong
    }

Not exactly sure what you're trying to do, but try-catch blocks work like this: 不完全确定你要做什么,但try-catch块的工作方式如下:

try{ 
    throw new Exception("Example exception");
}
catch(Exception e){
    System.out.println( "Exception caught: " + e.getMessage() );
}

You'll also have to modify the method that you are trying so that it throws the Exception you're looking for: 您还必须修改您正在尝试的方法,以便它抛出您正在寻找的Exception:

public void doSomething(String blah) throws Exception

Catching an exception is as simple as: 捕获异常非常简单:

try{
  //Some code that throws MyExceptionClass
}catch(MyException e){
  //Some code that handles the exception e
}

Throwing an exception is as simple as: 抛出异常很简单:

throw new MyException(some, parameters, of, your choice);

If your exception doesn't descend from RuntimeException then you must declare the the method throws it: 如果您的异常不是从RuntimeException下降,那么您必须声明该方法抛出它:

public void myExceptionCausingMethod() throws MyException{
  //Method code
}

The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. try / catch语句包含一些代码,用于处理该代码中可能出现的错误和异常。

public void input(Scanner in) throws InvalidRankException {
  super.input(in);

  if (in.hasNext()) {
    try {     
      title = Enum.valueOf(Title.class, in.next());
    } catch(InvalidRankException ire) {
      //You've hit the exception, code in here how to handle the situation
    }
  }
}

There's two issues here: 这里有两个问题:

  1. Enum won't return an invalid rank/title 枚举不会返回无效的等级/头衔
  2. InvalidRankException doesn't test for anything to cause it to fire. InvalidRankException不会测试导致它触发的任何内容。

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

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