Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I've already made the Exception, at the bottom of the code. But I've never used a Try/Catch Block before and am not sure how to implement it.

The Exception is if a rank that isn't listed under the enum is entered. I need to use a toString with the caught exception as well, but I'm pretty sure I can figure that one out.

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: ");

      }   
  }
}
like image 946
Tyler Avatar asked Feb 20 '26 23:02

Tyler


1 Answers

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. 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.
  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? What is display overriding? I'd recommend ditching display and sticking with toString.
  5. Your input method makes no sense whatsoever.
  6. Why is that Exception an inner class?
like image 52
duffymo Avatar answered Feb 23 '26 12:02

duffymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!