【问题标题】:How do I get try and catch to work in my code?如何让 try and catch 在我的代码中工作?
【发布时间】:2020-09-15 06:12:19
【问题描述】:

目标:当调用“initializeDriver”时,我不想在另一个类中继续抛出 IOexception。

如何正确地在我的代码中实现“try”和“catch”?这是我的尝试,但是,它无法正常工作。我试过环顾四周,但我可能没有正确理解它。

这是我的 gitHub 的链接,以防有人想查看:https://github.com/intuitive86/Sample_Driver_Test

package resources;

import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Base {

  public WebDriver driver;
  protected Properties dataProperties;

  public WebDriver initializeDriver() throws IOException {
    // Create global property file
    dataProperties = new Properties();
    InputStream dataPropertiesInputStream = null;
    try{
      InputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
      dataProperties.load(dataPropertiesInputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    String browserName = dataProperties.getProperty("browser");
    System.out.println(browserName);

    if (browserName.equals("chrome")) {
      WebDriverManager.chromedriver().setup();
      driver = new ChromeDriver();
    } else if (browserName.equals("firefox")) {
      WebDriverManager.firefoxdriver().setup();
      driver = new FirefoxDriver();
    }
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    return driver;
  }
}

【问题讨论】:

    标签: java selenium intellij-idea webdriver browser-automation


    【解决方案1】:

    你的问题我不清楚。据我了解,您需要隐藏从另一个区域显示的 IOException。

    try{
      InputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
      dataProperties.load(dataPropertiesInputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    

    从 catch 块中删除 e.printStackTrace(); 并提供一些记录器。

    try{
      InputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
      dataProperties.load(dataPropertiesInputStream);
    } catch (IOException e) {
      logger.error("I got IO exception, no need to worry, it's normal", e.getMessage());
    }
    

    【讨论】:

    • 感谢您的回复。你理解正确。每当我进入另一个类并使用extends 到我的“基础”类时,我想调用 WebDriver initializeDriver 而不必继续添加throws IOexception,因为我的基础类已设置为考虑到每次我使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多