How do I cleanly catch Exceptions?

GLVGLV
edited May 2018 in Questions about Code

Hello,

I get a "java.net.UnknownHostException" in the example I provided if there is no network connection. In my full blown code I get a "NullPointerException" also displayed in the bar above console.

You have to disable network to see the error! The code works if there is a network connection and URL is correct and available and displays retrieved data in console.

If you click on sketch window it will loop() and you will try to access the url. I did this so you do not keep retrieving data in an endless loop!

My code works for what I am doing.

Is there a better way to catch an Exception such as this? And not fill console with an error message.

String text = "";
String url = null;

// Added missing code that was in a tab
XML xml;
boolean testNull = false;

public void setup() 
  {
  size(200, 200);     
  }

public void draw() 
  {
  url = "http://" + "www.yr.no/place/Ecuador/Galapagos/Seymour/forecast.xml";
  loadxml();
  noLoop();
  }

void mousePressed() 
  {
  loop();
  }

void loadxml()
  {
  try
    {
    xml = loadXML(url);
    }
  catch (NullPointerException nullPointer)
    {
    testNull = true;
    }   

    println(testNull);

  if (testNull == false)
    {  
  // Load the XML document
    xml = loadXML(url);  

    XML credit = xml.getChild("credit/link");
    println(credit.getString("text"));
    text = credit.getString("text");
    println(credit.getString("url"));
    url = credit.getString("url");  
    }
  else
    {
    text = ("Unavailable"); 
    url = ("Unavailable");
    println(text);
    println(url);
    }  
  }  

Capture

Answers

Sign In or Register to comment.