Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6184617
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T01:34:05+00:00 2026-05-24T01:34:05+00:00

I came across the problem described in Checking If alert exists before switching to

  • 0

I came across the problem described in Checking If alert exists before switching to it. I find horrible to capture a NullPointerException. Has anyone solved this problem more elegantly?

My current solution uses a wait that captures the NPE. The client code just have to invoke waitForAlert(driver, TIMEOUT):

/**
 * If no alert is popped-up within <tt>seconds</tt>, this method will throw
 * a non-specified <tt>Throwable</tt>.
 * 
 * @return alert handler
 * @see org.openqa.selenium.support.ui.Wait.until(com.​google.​common.​base.Function)
 */
public static Alert waitForAlert(WebDriver driver, int seconds) {
    Wait<WebDriver> wait = new WebDriverWait(driver, seconds);
    return wait.until(new AlertAvailable());
}

private static class AlertAvailable implements ExpectedCondition<Alert> {
    private Alert alert = null;
    @Override
    public Alert apply(WebDriver driver) {
        Alert result = null;
        if (null == alert) {
            alert = driver.switchTo().alert();
        }

        try {
            alert.getText();
            result = alert;
        } catch (NullPointerException npe) {
            // Getting around https://groups.google.com/d/topic/selenium-users/-X2XEQU7hl4/discussion
        }
        return result;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T01:34:05+00:00Added an answer on May 24, 2026 at 1:34 am

    Based upon @Joe Coder answer, a simplified version of this wait would be:

    /**
     * If no alert is popped-up within <tt>seconds</tt>, this method will throw
     * a non-specified <tt>Throwable</tt>.
     * 
     * @return alert handler
     * @see org.openqa.selenium.support.ui.Wait.until(com.​google.​common.​base.Function)
     */
    public static Alert waitForAlert(WebDriver driver, int seconds) {
        Wait<WebDriver> wait = new WebDriverWait(driver, seconds)
            .ignore(NullPointerException.class);
        return wait.until(new AlertAvailable());
    }
    
    private static class AlertAvailable implements ExpectedCondition<Alert> {
        @Override
        public Alert apply(WebDriver driver) {
            Alert alert = driver.switchTo().alert();
            alert.getText();
            return alert;
        }
    }
    

    I have written a short test to proof the concept:

    import com.google.common.base.Function;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.concurrent.TimeUnit;
    import org.junit.Test;
    import org.openqa.selenium.support.ui.FluentWait;
    import org.openqa.selenium.support.ui.Wait;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class TestUntil {
        private static Logger log = LoggerFactory.getLogger(TestUntil.class);
    
        @Test
        public void testUnit() {
            Wait<MyObject> w = new FluentWait<MyObject>(new MyObject())
                    .withTimeout(30, TimeUnit.SECONDS)
                    .ignoring(NullPointerException.class);
            log.debug("Waiting until...");
            w.until(new Function<MyObject, Object>() {
                @Override
                public Object apply(MyObject input) {
                    return input.get();
                }
            });
            log.debug("Returned from wait");
        }
    
        private static class MyObject {
            Iterator<Object> results = new ArrayList<Object>() {
                {
                    this.add(null);
                    this.add(null);
                    this.add(new NullPointerException("NPE ignored"));
                    this.add(new RuntimeException("RTE not ignored"));
                }
            }.iterator();
            int i = 0;
            public Object get() {
                log.debug("Invocation {}", ++i);
                Object n = results.next();
                if (n instanceof RuntimeException) {
                    RuntimeException rte = (RuntimeException)n;
                    log.debug("Throwing exception in {} invocation: {}", i, rte);
                    throw rte;
                }
                log.debug("Result of invocation {}: '{}'", i, n);
                return n;
            }
        }
    }
    

    In this code, in the until the MyObject.get() is invoked four times. The third time, it throws an ignored exception, but the last one throws a not-ignored exception, interrupting the wait.

    The output (simplified for readability):

    Waiting until...
    Invocation 1
    Result of invocation 1: 'null'
    Invocation 2
    Result of invocation 2: 'null'
    Invocation 3
    Throwing exception in 3 invocation: java.lang.NullPointerException: NPE ignored
    Invocation 4
    Throwing exception in 4 invocation: java.lang.RuntimeException: RTE not ignored
    
    ------------- ---------------- ---------------
    Testcase: testUnit(org.lila_project.selenium_tests.tmp.TestUntil):  Caused an ERROR
    RTE not ignored
    java.lang.RuntimeException: RTE not ignored
        at org.lila_project.selenium_tests.tmp.TestUntil$MyObject$1.<init>(TestUntil.java:42)
        at org.lila_project.selenium_tests.tmp.TestUntil$MyObject.<init>(TestUntil.java:37)
        at org.lila_project.selenium_tests.tmp.TestUntil$MyObject.<init>(TestUntil.java:36)
        at org.lila_project.selenium_tests.tmp.TestUntil.testUnit(TestUntil.java:22)
    

    Note that as the RuntimeException is not ignored, the “Returned from wait” log is not printed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I came across a problem while updating a typed DataTable that has a primary
Recently I came across a problem that asks to find out the non-unique characters
i recently came across a problem with my parallel program. Each process has several
I came across a problem in my current application that required fiddling with the
I came across this problem while preparing for an interview and curious to know
I came across a problem I cannot solve on my own concerning the downloadable
Today I came across a problem where someone had accidentally committed a proj.user file
I am new to creating Java web applications and came across this problem when
I am watching a video about [LINQ][1] and came across a problem. In this
Guys, I've came across this problem I can't resolve myselg, I'm pretty sure I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.