How to catch thrown exception

Associate
Joined
11 Jul 2009
Posts
1,318
Hi , the exception in the below code, how can I catch the exception with a try catch block?

Code:
public void setFirstName(String firstName){
 
      if(firstName.length() < 2){
 
          throw new IllegalArgumentException("NAME LENGTH IS TOO SHORT! ");
      }
      this.firstName = firstName;
  }

I want to catch it in the tester class

Code:
public class Car_Tester{
   public static void main (String[] args){
 
      CarType1 c1 = new CarType1("B.M.W","Series 7",100,51000,true);
      System.out.println(c1.toString());
      c1.move();
 
      try{
        setPrice(int price);
      }
      catch(IllegalArgumentException e)
      {
        System.out.println(" error");
      }
 
   }

What I tried didn't work, I basically want it to display a message instead of crashing the program.

Is it possible to do this?

thanks
 
Back
Top Bottom