0

Why I stopped using try-catch everywhere (and what I do instead)

Early in my career, I wrapped everything in try-catch blocks. Every function, every API call, every database query. My code looked like a Russian nesting doll of exception handlers.

Then I realized: most of those try-catch blocks were hiding bugs, not handling errors.

The Problem

try:
    user = get_user(user_id)
        orders = get_orders(user.id)
            total = calculate_total(orders)
            except Exception:
                return None  # 🤡
                ```
                
                This catches *everything* — including typos, null references, and logic errors that should crash loudly. Returning `None` means the bug surfaces 3 layers up as a mysterious `NoneType has no attribute` error.
                
                ## What I Do Instead
                
                ### 1. Let it crash (in development)
                
                Unexpected errors should be loud. If `get_user` fails because of a bad query, I *want* to see the stack trace immediately — not a silent `None`.
                
                ### 2. Only catch what you can handle
                
                ```python
                try:
                    response = requests.get(url, timeout=5)
                    except requests.Timeout:
                        return cached_response  # I know what to do here
                        ```
                        
                        Catch specific exceptions. Have a concrete recovery plan. If you can't recover, don't catch.
                        
                        ### 3. Use Result types for expected failures
                        
                        ```python
                        def parse_config(path: str) -> Result[Config, str]:
                            if not path.exists():
                                    return Err("Config file not found")
                                        return Ok(Config.from_file(path))
                                        ```
                                        
                                        This makes failure an explicit part of the return type. Callers *must* handle both cases.
                                        
                                        ### 4. Fail at the boundary
                                        
                                        Put error handling at system boundaries — API endpoints, CLI entry points, message consumers. Let errors propagate naturally through your business logic.
                                        
                                        ```python
                                        @app.route('/api/orders')
                                        def get_orders():
                                            try:
                                                    return jsonify(order_service.list_orders())
                                                        except OrderServiceError as e:
                                                                return jsonify({"error": str(e)}), 400
                                                                ```
                                                                
                                                                ## The Rule
                                                                
                                                                **If your catch block is `pass`, `return None`, or `print(e)`, delete the try-catch.** You're not handling the error — you're hiding it.
                                                                
                                                                Better to crash with a clear stack trace than to silently corrupt data 3 hours into a production run.
                                                                
                                                                ---
                                                                
                                                                How do you handle errors in your projects? I'd love to hear different approaches.

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí