1

Trying to find the correct error when args[0]is not found.

class Main
{
    public static void main(String[] args)
    {
        try 
        {
            String filename = args[0];
        }
        catch (ExceptionInThread e)
        {
            System.out.println(“No file found”);
        }
    }
}

I keep getting the samme error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: o at Main.main(Main.java:9)

Can someone tell me how I can find the correct error to catch?

froffen
  • 27
  • 5
  • 1
    `args.length`.... No need to generate the exception when you can just check if it should exist. – SomeJavaGuy Feb 15 '17 at 07:30
  • 4
    "Can someone tell me how I can find the correct error to catch?" The error message mentions the exception to catch... – tkausl Feb 15 '17 at 07:32
  • And the reason that your current approach is failing is because you are catching the wrong exception. However, that's not the best solution anyway. The best solution is to avoid throwing it in the first place. See the linked Q&A – Stephen C Feb 15 '17 at 07:56
  • @StephenC I don't think, that this is a duplicate of the linked question, although it is an easy one, that has been asked in similar ways before. It's not about preventing OutOfBounds, it's about how to find and catch the right Exception. – ppasler Feb 15 '17 at 08:13
  • The OP asks how to catch the exception. However, the correct solution is to prevent the exception, not try to catch it. – Stephen C Feb 15 '17 at 08:32

1 Answers1

0

As all Exceptions inherit from Exception, this is the catch all:

public static void main(String[] args){
    try {
        String filename = args[0];
    } catch (Exception e) {
        System.out.println("No file found");
    }
}

But this is generally bad practice, as you catch every type of Error - don't do it.

To answer you question: You find the Exception name / type in your error message Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException, where ArrayIndexOutOfBoundsException is the Exception to catch:

catch (ArrayIndexOutOfBoundsException e) What you did was catching the wrong Exception and that's why the error is not catched. In your case this is also not the cleanest way to go.

The best way in my eyes, is to check the args array before trying to access it:

ìf args.length > 0

If you want to print an error, you may use System.err.println("No file found"); instead of System.out

ppasler
  • 3,579
  • 5
  • 31
  • 51
  • 1
    Showing people how to catch `Exception` is a bad idea. Chances are that someone will stop reading as soon as they see code .... and copy your example of bad code. – Stephen C Feb 15 '17 at 08:00
  • You are right, that's why I also said it is bad practice. – ppasler Feb 15 '17 at 08:14