Program only throws exception when variable is defined in “try”Do try/catch blocks hurt performance when exceptions are not thrown?Is it a good practice to use try-except-else in Python?Exception try and catch on split name into first and lastWhy is “except: pass” a bad programming practice?How to prevent a runtime error to stop the rest of the code in try/catch from executing?Python looping with try and exceptStruggling with try/catch InputMismatch Exception and retrieving data from an arrayPython ValueError exception - Name “a” is not defined errorrequests.get returns 400 bad url when given a variable containing a url, but not when given a string with the same urlJava JSoup Exception ignores try catch?

Pronouncing Dictionary.com's W.O.D "vade mecum" in English

Infinite past with a beginning?

Compute hash value according to multiplication method

Why is an old chain unsafe?

Download, install and reboot computer at night if needed

A function which translates a sentence to title-case

What are these boxed doors outside store fronts in New York?

How to make payment on the internet without leaving a money trail?

I see my dog run

Is it possible to make sharp wind that can cut stuff from afar?

Draw simple lines in Inkscape

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

The use of multiple foreign keys on same column in SQL Server

How to type dʒ symbol (IPA) on Mac?

Can I make popcorn with any corn?

Is there really no realistic way for a skeleton monster to move around without magic?

Modification to Chariots for Heavy Cavalry Analogue for 4-armed race

How is it possible for user to changed after storage was encrypted? (on OS X, Android)

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

How is it possible to have an ability score that is less than 3?

What would happen to a modern skyscraper if it rains micro blackholes?

Patience, young "Padovan"

How old can references or sources in a thesis be?



Program only throws exception when variable is defined in “try”


Do try/catch blocks hurt performance when exceptions are not thrown?Is it a good practice to use try-except-else in Python?Exception try and catch on split name into first and lastWhy is “except: pass” a bad programming practice?How to prevent a runtime error to stop the rest of the code in try/catch from executing?Python looping with try and exceptStruggling with try/catch InputMismatch Exception and retrieving data from an arrayPython ValueError exception - Name “a” is not defined errorrequests.get returns 400 bad url when given a variable containing a url, but not when given a string with the same urlJava JSoup Exception ignores try catch?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am trying to write a program that will read a webpage. The following code is not valid:



String[] lines;
try
lines = loadStrings(url);

catch(IOException e)
return;



But this code is:



try 
String[] lines = loadStrings(url);

catch(IOException e)
return;



I cannot use the code in the second example because I need to use the variable "lines" later in the program. Is there some other way to catch this exception (504 error)?



Example:



PFont f;
String webpage;

void setup()
size(400, 400);
f = createFont("Arial", 16);



void draw()
background(255);
textFont(f);
fill(0);
text("Press Return to Start", 25, 90);



void keyPressed()
if (key == 'n')
webpage = "processing.org";
loadData(webpage);




void loadData(String webpage)

String url = "www.processing.org";
try
String[] lines = loadStrings(url);

catch(IOException e)
return;

saveStrings("Stuff on Webpage.txt", lines);



This is where the program crashes:



java.io.IOException: Server returned HTTP response code: 504 for URL: http://www.processing.org/


In the event of this exception, I would like the program to exit out of the loadData function and continue with keyPressed.










share|improve this question
























  • Can you please post a Minimal, Complete, and Verifiable example?

    – Kevin Workman
    Mar 22 at 0:57











  • I have updated it with some code.

    – user11006750
    Mar 23 at 2:13

















1















I am trying to write a program that will read a webpage. The following code is not valid:



String[] lines;
try
lines = loadStrings(url);

catch(IOException e)
return;



But this code is:



try 
String[] lines = loadStrings(url);

catch(IOException e)
return;



I cannot use the code in the second example because I need to use the variable "lines" later in the program. Is there some other way to catch this exception (504 error)?



Example:



PFont f;
String webpage;

void setup()
size(400, 400);
f = createFont("Arial", 16);



void draw()
background(255);
textFont(f);
fill(0);
text("Press Return to Start", 25, 90);



void keyPressed()
if (key == 'n')
webpage = "processing.org";
loadData(webpage);




void loadData(String webpage)

String url = "www.processing.org";
try
String[] lines = loadStrings(url);

catch(IOException e)
return;

saveStrings("Stuff on Webpage.txt", lines);



This is where the program crashes:



java.io.IOException: Server returned HTTP response code: 504 for URL: http://www.processing.org/


In the event of this exception, I would like the program to exit out of the loadData function and continue with keyPressed.










share|improve this question
























  • Can you please post a Minimal, Complete, and Verifiable example?

    – Kevin Workman
    Mar 22 at 0:57











  • I have updated it with some code.

    – user11006750
    Mar 23 at 2:13













1












1








1








I am trying to write a program that will read a webpage. The following code is not valid:



String[] lines;
try
lines = loadStrings(url);

catch(IOException e)
return;



But this code is:



try 
String[] lines = loadStrings(url);

catch(IOException e)
return;



I cannot use the code in the second example because I need to use the variable "lines" later in the program. Is there some other way to catch this exception (504 error)?



Example:



PFont f;
String webpage;

void setup()
size(400, 400);
f = createFont("Arial", 16);



void draw()
background(255);
textFont(f);
fill(0);
text("Press Return to Start", 25, 90);



void keyPressed()
if (key == 'n')
webpage = "processing.org";
loadData(webpage);




void loadData(String webpage)

String url = "www.processing.org";
try
String[] lines = loadStrings(url);

catch(IOException e)
return;

saveStrings("Stuff on Webpage.txt", lines);



This is where the program crashes:



java.io.IOException: Server returned HTTP response code: 504 for URL: http://www.processing.org/


In the event of this exception, I would like the program to exit out of the loadData function and continue with keyPressed.










share|improve this question
















I am trying to write a program that will read a webpage. The following code is not valid:



String[] lines;
try
lines = loadStrings(url);

catch(IOException e)
return;



But this code is:



try 
String[] lines = loadStrings(url);

catch(IOException e)
return;



I cannot use the code in the second example because I need to use the variable "lines" later in the program. Is there some other way to catch this exception (504 error)?



Example:



PFont f;
String webpage;

void setup()
size(400, 400);
f = createFont("Arial", 16);



void draw()
background(255);
textFont(f);
fill(0);
text("Press Return to Start", 25, 90);



void keyPressed()
if (key == 'n')
webpage = "processing.org";
loadData(webpage);




void loadData(String webpage)

String url = "www.processing.org";
try
String[] lines = loadStrings(url);

catch(IOException e)
return;

saveStrings("Stuff on Webpage.txt", lines);



This is where the program crashes:



java.io.IOException: Server returned HTTP response code: 504 for URL: http://www.processing.org/


In the event of this exception, I would like the program to exit out of the loadData function and continue with keyPressed.







html url try-catch processing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 16:10









Kevin Workman

34.4k54273




34.4k54273










asked Mar 22 at 0:54









user11006750user11006750

83




83












  • Can you please post a Minimal, Complete, and Verifiable example?

    – Kevin Workman
    Mar 22 at 0:57











  • I have updated it with some code.

    – user11006750
    Mar 23 at 2:13

















  • Can you please post a Minimal, Complete, and Verifiable example?

    – Kevin Workman
    Mar 22 at 0:57











  • I have updated it with some code.

    – user11006750
    Mar 23 at 2:13
















Can you please post a Minimal, Complete, and Verifiable example?

– Kevin Workman
Mar 22 at 0:57





Can you please post a Minimal, Complete, and Verifiable example?

– Kevin Workman
Mar 22 at 0:57













I have updated it with some code.

– user11006750
Mar 23 at 2:13





I have updated it with some code.

– user11006750
Mar 23 at 2:13












1 Answer
1






active

oldest

votes


















0














Let's look at this code:



String message;

if(random(1) < .5)
message = "hello";


println(message);



This code will generate an error that says message cannot be resolved to a variable. This is because the compiler is smart enough to know that depending on what the if statement does, message might not contain a value. Processing / Java does not assign a default value to local variables.



We could fix this compiler error by assigning a default value ourselves:



String message = null;

if(random(1) < .5)
message = "hello";


println(message);



Now message has a default value of null, which matches what happens with sketch / class variables by default.



Another way we could fix this is by putting the println() call inside the if statement:



String message;

if(random(1) < .5)
message = "hello";
println(message);



We could simplify this a bit:



if(random(1) < .5) 
String message = "hello";
println(message);



Now, back to your code:



try 
String[] lines = loadStrings(url);

catch(IOException e)
return;

saveStrings("Stuff on Webpage.txt", lines);


This doesn't work because lines is declared inside the try block, so it goes out of scope outside of that block, and you can't use it afterwards.



String[] lines;
try
lines = loadStrings(url);

catch(IOException e)
return;

saveStrings("Stuff on Webpage.txt", lines);


This doesn't work, because the compiler is not smart enough to see that return statement. It just knows that one branch of the code skips over the lines = loadStrings(url); line, so it knows that lines might be unassigned when you try to use it.



You can fix this by either assigning a default value yourself, or moving everything to be inside the same block, just like we did with our simplified example above.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291364%2fprogram-only-throws-exception-when-variable-is-defined-in-try%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Let's look at this code:



    String message;

    if(random(1) < .5)
    message = "hello";


    println(message);



    This code will generate an error that says message cannot be resolved to a variable. This is because the compiler is smart enough to know that depending on what the if statement does, message might not contain a value. Processing / Java does not assign a default value to local variables.



    We could fix this compiler error by assigning a default value ourselves:



    String message = null;

    if(random(1) < .5)
    message = "hello";


    println(message);



    Now message has a default value of null, which matches what happens with sketch / class variables by default.



    Another way we could fix this is by putting the println() call inside the if statement:



    String message;

    if(random(1) < .5)
    message = "hello";
    println(message);



    We could simplify this a bit:



    if(random(1) < .5) 
    String message = "hello";
    println(message);



    Now, back to your code:



    try 
    String[] lines = loadStrings(url);

    catch(IOException e)
    return;

    saveStrings("Stuff on Webpage.txt", lines);


    This doesn't work because lines is declared inside the try block, so it goes out of scope outside of that block, and you can't use it afterwards.



    String[] lines;
    try
    lines = loadStrings(url);

    catch(IOException e)
    return;

    saveStrings("Stuff on Webpage.txt", lines);


    This doesn't work, because the compiler is not smart enough to see that return statement. It just knows that one branch of the code skips over the lines = loadStrings(url); line, so it knows that lines might be unassigned when you try to use it.



    You can fix this by either assigning a default value yourself, or moving everything to be inside the same block, just like we did with our simplified example above.






    share|improve this answer



























      0














      Let's look at this code:



      String message;

      if(random(1) < .5)
      message = "hello";


      println(message);



      This code will generate an error that says message cannot be resolved to a variable. This is because the compiler is smart enough to know that depending on what the if statement does, message might not contain a value. Processing / Java does not assign a default value to local variables.



      We could fix this compiler error by assigning a default value ourselves:



      String message = null;

      if(random(1) < .5)
      message = "hello";


      println(message);



      Now message has a default value of null, which matches what happens with sketch / class variables by default.



      Another way we could fix this is by putting the println() call inside the if statement:



      String message;

      if(random(1) < .5)
      message = "hello";
      println(message);



      We could simplify this a bit:



      if(random(1) < .5) 
      String message = "hello";
      println(message);



      Now, back to your code:



      try 
      String[] lines = loadStrings(url);

      catch(IOException e)
      return;

      saveStrings("Stuff on Webpage.txt", lines);


      This doesn't work because lines is declared inside the try block, so it goes out of scope outside of that block, and you can't use it afterwards.



      String[] lines;
      try
      lines = loadStrings(url);

      catch(IOException e)
      return;

      saveStrings("Stuff on Webpage.txt", lines);


      This doesn't work, because the compiler is not smart enough to see that return statement. It just knows that one branch of the code skips over the lines = loadStrings(url); line, so it knows that lines might be unassigned when you try to use it.



      You can fix this by either assigning a default value yourself, or moving everything to be inside the same block, just like we did with our simplified example above.






      share|improve this answer

























        0












        0








        0







        Let's look at this code:



        String message;

        if(random(1) < .5)
        message = "hello";


        println(message);



        This code will generate an error that says message cannot be resolved to a variable. This is because the compiler is smart enough to know that depending on what the if statement does, message might not contain a value. Processing / Java does not assign a default value to local variables.



        We could fix this compiler error by assigning a default value ourselves:



        String message = null;

        if(random(1) < .5)
        message = "hello";


        println(message);



        Now message has a default value of null, which matches what happens with sketch / class variables by default.



        Another way we could fix this is by putting the println() call inside the if statement:



        String message;

        if(random(1) < .5)
        message = "hello";
        println(message);



        We could simplify this a bit:



        if(random(1) < .5) 
        String message = "hello";
        println(message);



        Now, back to your code:



        try 
        String[] lines = loadStrings(url);

        catch(IOException e)
        return;

        saveStrings("Stuff on Webpage.txt", lines);


        This doesn't work because lines is declared inside the try block, so it goes out of scope outside of that block, and you can't use it afterwards.



        String[] lines;
        try
        lines = loadStrings(url);

        catch(IOException e)
        return;

        saveStrings("Stuff on Webpage.txt", lines);


        This doesn't work, because the compiler is not smart enough to see that return statement. It just knows that one branch of the code skips over the lines = loadStrings(url); line, so it knows that lines might be unassigned when you try to use it.



        You can fix this by either assigning a default value yourself, or moving everything to be inside the same block, just like we did with our simplified example above.






        share|improve this answer













        Let's look at this code:



        String message;

        if(random(1) < .5)
        message = "hello";


        println(message);



        This code will generate an error that says message cannot be resolved to a variable. This is because the compiler is smart enough to know that depending on what the if statement does, message might not contain a value. Processing / Java does not assign a default value to local variables.



        We could fix this compiler error by assigning a default value ourselves:



        String message = null;

        if(random(1) < .5)
        message = "hello";


        println(message);



        Now message has a default value of null, which matches what happens with sketch / class variables by default.



        Another way we could fix this is by putting the println() call inside the if statement:



        String message;

        if(random(1) < .5)
        message = "hello";
        println(message);



        We could simplify this a bit:



        if(random(1) < .5) 
        String message = "hello";
        println(message);



        Now, back to your code:



        try 
        String[] lines = loadStrings(url);

        catch(IOException e)
        return;

        saveStrings("Stuff on Webpage.txt", lines);


        This doesn't work because lines is declared inside the try block, so it goes out of scope outside of that block, and you can't use it afterwards.



        String[] lines;
        try
        lines = loadStrings(url);

        catch(IOException e)
        return;

        saveStrings("Stuff on Webpage.txt", lines);


        This doesn't work, because the compiler is not smart enough to see that return statement. It just knows that one branch of the code skips over the lines = loadStrings(url); line, so it knows that lines might be unassigned when you try to use it.



        You can fix this by either assigning a default value yourself, or moving everything to be inside the same block, just like we did with our simplified example above.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 16:09









        Kevin WorkmanKevin Workman

        34.4k54273




        34.4k54273





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291364%2fprogram-only-throws-exception-when-variable-is-defined-in-try%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현