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
 
The setFirstName method doesn't get called from the tester class so you wont be able to catch that error from that point in the code.
You've got the try/catch syntax correct but you've only got it around the setPrice method.

If you do the setFirstName call inside the try, it should work:
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);
        setFirstName("A");
      }
      catch(IllegalArgumentException e)
      {
        System.out.println(" error");
      }
 
   }
 
Back
Top Bottom