Revise the exception handling in the code to adhere to conventional programming standards. Please ensure that the error management processes are clear, efficient, and robust.
```

class PytestSetupError(AssistantError):
    error_messages = {
        8001: "Setup failed: Unable to create directory.",
        8002: "Setup failed: Unable to write code to test file.",
        8003: "Setup failed: Unable to write pytest.ini file.",
        8004: "Setup failed: Environment creation error.",
    }

def create_environment(environment, requirements, packages):
    """Sets up a virtual environment and installs required packages."""
    try:
        if platform.system().lower() == "linux":
            commands = [
                f'python -m venv "{environment}"',
                f'. "{environment}/bin/activate"',
                f"python -m pip install --upgrade pip",
                f'pip install -r "{requirements}"',
            ]
        else:
            commands = [
                "cmd /c",
                f'python -m venv "{environment}"',
                f'"{environment}/Scripts/activate"',
                f'pip install -r "{requirements}"',
            ]
        for package in packages:
            commands.append(
                f"pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org --trusted github.com {package}"
            )
        logger.info(f"Creating Environment :{commands}")
        env_creation_stdout, env_creation_stderr, env_creation_return_code = command_prompt(
            commands
        )

        if env_creation_return_code == 0:
            logger.info(f"Environment created Successfully : {environment}")
            json_logger.info(env_creation_stdout)
            json_logger.info(env_creation_stderr)
            return True
        else:
            logger.info(f"Environment creation Failed : {environment}")
            json_logger.error(env_creation_stdout)
            json_logger.error(env_creation_stderr)
            return False
    except Exception as e:
        logger.exception(f"An unexpected error occurred while creating the environment: {e}")
        raise

def pytest_setup(code, repo_path, test_dir, test_file_name):
    """Create necessary test directory and files."""
    try:
        if not os.path.exists(test_dir):
            os.makedirs(test_dir)
            logger.info(f"Test directory created: {test_dir}")

        with open(f"{test_dir}/{test_file_name}", "w", encoding="utf-8") as script_file:
            script_file.write(code)
            logger.info(f"Test code saved in: {test_dir}/{test_file_name}")
    except OSError as e:
        raise PytestSetupError(8002, str(e))

    try:
        with open(f"{repo_path}/pytest.ini", "w") as script_file:
            script_file.write("[pytest]\npythonpath = src")
            logger.info(f"pytest.ini created in location: {repo_path}/pytest.ini")
    except OSError as e:
        raise PytestSetupError(8003, str(e))

    try:
        if not os.path.exists(f"env/{os.path.basename(repo_path)}"):
            packages = [
                "pytest==7.4.4",
                "pytest-cov==5.0.0",
                "pytest-html==4.1.1",
                "pytest-json-report==1.5.0",
                "pytest-metadata==2.0.4",
            ]
            environment = os.path.abspath(f"env/{os.path.basename(repo_path)}")
            env_creation_success = create_environment(
                environment, f"{repo_path}/requirements.txt", packages
            )

            if env_creation_success:
                logger.info("Pytest setup successful")
                return True
            else:
                return False
    except Exception as e:
        logger.exception(f"Unexpected error during pytest setup: {e}")
        raise PytestSetupError(8004, f"Unexpected error: {str(e)}")


def code_runner(state):
    logger.info("START CodeRunner")
    test_dir = state["metadata"]["test_dir"]
    repo_path = state["metadata"]["repo_path"]
    object_name = state["metadata"]["object_name"]
    iteration = state["fca_remaining_iterations"]
    file_name = state["metadata"]["file_name"]
    code = state["test_code"]

    test_file_name = f"test_{object_name}_{file_name}"
    json_report_file = f"{repo_path}/test/reports/pytest_test_report_{iteration}_{object_name}_{os.path.splitext(file_name)[0]}.json"
    try:
        pytest_setup_sucess = pytest_setup(code, repo_path, test_dir, test_file_name)
        if not pytest_setup_sucess:
            raise PytestSetupError(8004, "Pytest setup failed")
    except PytestSetupError as e:
        raise 
    try:
        response = run_pytest_code(repo_path, test_file_name, json_report_file)
    except:
        pass
    # writing the outputs to a file
    results_logger.save_to_file(
        path=f"pytest_reports/pytest_report_iter_{iteration}.txt", data=response
    )
    with open(json_report_file, "r", encoding="utf-8") as file:
        data = json.load(file)
    report_str = generate_pytest_report(data)
    results_logger.save_to_file(
        path=f"pytest_reports/pytest_report_{iteration}.txt", data=report_str
    )

    return {"pytest_report_json": data, "pytest_report_str": report_str}
```