Causing a MalformedURLException (Android)

1.1k views Asked by At

I am trying to induce a MalformedURLException in my code to test my handling of it, however no matter what I try I cannot seem to cause it. (I've passed in a complete nonsense non-url string and it still does not arise, I simply get a null response)

I am aware that android developers reference describes:

This exception is thrown when a program attempts to create an URL from an incorrect specification.

I was wondering how do I create/provide such an incorrect specification

This is the code I'm trying to execute

     try {
        HttpData data = request.composeHttpData();
        //URL url = new URL(composeUrl(data));
        URL url2 = new URL("mydomain:-2/invalidPort");
        HttpsURLConnection conn = (HttpsURLConnection) getHttpClient().open(url2);
        conn.setRequestMethod(data.getMethod());

        //authentication
        addAuthentication(conn);

        //post body
        if (data.getMethod() == POST) {
            conn.setDoOutput(true);
            data.writePostBody(conn.getOutputStream());
            conn.getOutputStream().close();
        }

        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.consumeResponse(conn.getInputStream());
        }

        response.setResponseHttpCode(conn.getResponseCode());

    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new Error("Malformed URL encountered");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        return response;
    }

When I try to debug the code it seems to jump from the Url instantiation to the return statement.

2

There are 2 answers

5
dafi On BEST ANSWER

Pass a port number less than -1

    URL url = new URL("http://mydomain:-2/invalidPort");
0
Graham Borland On

How about

throw new MalformedURLException("Testing!");