Thoughts on using curly-brackets-less while loop with a try/catch?

I need to fetch data from an server that isn’t always reliable and unfortunately fixing that is out of my hands. My team determined we would attempt the request up to 3 times.

So I thought of using a try-catch inside the while loop but didn’t like the extra indentation for no good reason and thought to remove the braces from the while loop.

async function doAjax() {   const data = { /* stuff */ }   const retryLimit = 2;   let retryCount = 0;   let found = false;    while (!found && retryCount <= retryLimit) try {     let serverResponse = await $  .get("url", data);     // Do stuff   } catch (err) {     retryCount++;   }    // Do more stuff }

I know my team won’t be against this, but I still got curious if there’s a consensus or some reason in favor/against writing code this way. Thoughts?

Multiple null Checks or try/catch NullPointerException

There is A LOT of information online stating that you should NEVER catch a NullPointerException. Generally I agree, but I am wondering about this one case.

I have inherited code that requires me to access data that I need in the following way

context.getGrandParent().getParent().getChild().isRequired() 

There is no guarantee that any of the objects in this hierarchy will not be null. I have to enter a block if isRequired() returns true. First, and what I initially wrote, with null checks:

if(context != null    && context.getGrandParent() != null    && context.getGrandParent().getParent() != null    && context.getGrandParent().getParent().getChild() != null     && context.getGrandParent().getParent().getChild().isRequired() ){    // continue with business logic } else {    LOG.error("Unable to determine if processing is required."); }     // continue with other inherited code 

Setting aside that I could refactor this, perhaps for readability, wouldn’t it make more sense to do the following?

boolean isRequired = false; try {    isRequired = context.getGrandParent().getParent().getChild().isRequired(); } catch (NullPointerException npe) {    LOG.error("Unable to determine if processing is required."); }  if(isRequired){    // continue with business logic } // continue with other inherited code 

Try/Catch not working in PHP not catching Exception

Why Try/Catch not working ?

try {     $  tagsData = $  vid["items"][0]["snippet"]["tags"];     $  tagsArray = array();     $  tagsString = "";     for ($  x = 0; $  x < count($  tagsData); $  x++) {         $  tagsArray[$  x] = $  tagsData[$  x];         $  tagsString .= $  tagsArray[$  x] . "  ,  ";     }     echo $  tagsString; } catch (\Exception $  e) {     echo "There is no tags."; } 

there is some videos on youtube don’t has tags so $ tagsData will be null…

How can I fix this code to use try…catch?

static double trycatch(double newint)     {     double input = 0;     boolean thrown = true;     while (thrown == true)     {         try         {             thrown = false;             input = newint;         }         catch(InputMismatchException e)             {                 System.out.println("That is not a valid input. Please try again.");                 thrown = true;                 throw e;         }     }     return input; } 

I want this function to use try…catch but if the thing inputted is not a double, then the function fails at that line. How can I fix this?

A more functional try…catch construct in Java

I saw a question on Stack Overflow asking for a review of a custom try…catch construct that made use of Optionals, and got the idea to try writing my own version. Mine doesn’t use Optionals though. Each supplied catch handler is expected to return a value.

I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven’t written Java in a few years though, and I’m curious what can be improved.

Example of use:

Integer i =         new Try<>(()-> Integer.parseInt("f"))                   .catching(NumberFormatException.class, (e)-> 2)                   .catching(IllegalStateException.class, (e) -> 3)                   .andFinally(()-> System.out.println("Finally!"));  // Finally!  Integer j =         new Try<>(()-> Integer.parseInt("1"))                   .catching(NumberFormatException.class, (e) -> 2)                   .execute();  System.out.println(i); // 2 System.out.println(j); // 1 

Basically how it works is the Try object can have catching methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.

Major problems:

  • The need for .class is unfortunate. I couldn’t think of how else to have the caller indicate the class of exception to be caught though.

  • Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.

  • The need for execute when andFinally isn’t used. I can’t see how the class would know that all catches have been added though.

  • The need for new is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I’d need to do something like Try.tryMethod to reference it, which isn’t a whole lot better.

  • The check in andFinally seems like it’s unnecessary. Unless someone does something bizarre like:

    Try t = new Try<>(() -> null); t.andFinally(() -> {}); t.andFinally(() -> {}); 

    It shouldn’t be possible to add multiple finally blocks. I’m not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I’m not sure if that’s necessary.

Since this is basically just exercise code, I’d love to anything at all that could be improved here. This is the first Java I’ve really written in a few years, so I’m sure there’s lots that can be improved.

import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier;  public class Try<T> {     private Supplier<T> tryExpr;     private Map<Class, Function<Exception, T>> handlers = new HashMap<>();     private Runnable finallyExpr;      public Try(Supplier<T> tryExpr) {         this.tryExpr = tryExpr;     }      public Try<T> catching(Class ex, Function<Exception, T> handler) {         if(handlers.containsKey(ex)) {             throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");          } else {             handlers.put(ex, handler);              return this;         }     }      public T execute() {         try {             return tryExpr.get();          } catch (Exception e) {             if(handlers.containsKey(e.getClass())) {                 Function<Exception, T> handler = handlers.get(e.getClass());                  return handler.apply(e);              } else {                 throw e;             }          } finally {             if(finallyExpr != null) {                 finallyExpr.run();             }         }     }      public T andFinally (Runnable newFinallyExpr) {        if (finallyExpr == null) {            finallyExpr = newFinallyExpr;         } else {            throw new IllegalStateException("Cannot have multiple finally expressions");        }         return execute();     }  }