我如何让 try 和 catch 在我的代码中工作?

How do I get try and catch to work in my code?

目标:调用 'initializeDriver' 时,我不想在另一个 class.

中继续抛出 IOexception

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

这是我的 gitHub 的 link 以防有人想看一看: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;
  }
}

我不清楚你的问题。据我了解,您需要隐藏从另一个区域显示的 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());
}