Farooq Khan
Farooq Khan

Reputation: 305

What could be an alternative to nested exceptions in java?

My java program reads a file or a website and shows its contents on console. I am using nested try catch blocks. Is there another way of doing this, without using nested exceptions.

public static void main(String[] args) throws IOException
{
    try
    {
        // Reads from file
    }
    catch(FileNotFoundException fnf)
    {
        try
        {
            // Assuming the entered path is to a website, Reads from a webiste, 
        }
        catch(MalFormedURLException urlEx)
        {

        }
        catch(IOException f)
        {

        }
    }
    catch(IOException e)
    {

    }
}

Upvotes: 0

Views: 26

Answers (1)

michnovka
michnovka

Reputation: 3389

Change your logic.

public static void main(String[] args) throws IOException
{

    try
    {
        if(isUrl(args)){
            // Reads from website

        }else{
            // Reads from file
        }
    }
    catch(MalFormedURLException urlEx)
    {

    }
    catch(IOException f)
    {


    }
}

isUrl function checks if arg is url by checking for http:// or https:// prefix or whatever protocol you support. I do not provide code for it, but it should be fairly simple for you to code yourself.

Upvotes: 1

Related Questions