Bird
Raised Fist0
Flaskframework~20 mins

Exception handling in routes in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Exception Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a route raises a handled exception?

Consider this Flask route that raises a ValueError which is caught by a custom error handler. What will the client receive as a response?

Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/test')
def test_route():
    raise ValueError('Invalid value')

@app.errorhandler(ValueError)
def handle_value_error(e):
    return jsonify({'error': str(e)}), 400

# Assume app.run() is called elsewhere
ADefault Flask 500 Internal Server Error page
BEmpty response with status code 200
C{"error": "Invalid value"} with status code 400
DFlask debug traceback page
Attempts:
2 left
💡 Hint

Think about what happens when an exception is raised and a matching error handler exists.

📝 Syntax
intermediate
2:00remaining
Which option correctly registers an error handler for HTTP 404 errors?

In Flask, you want to create a custom response for 404 Not Found errors. Which code snippet correctly registers this handler?

A
@app.route('/404')
def not_found():
    return 'Page not found', 404
B
@app.errorhandler(404)
def not_found(e):
    return 'Page not found', 404
C
@app.errorhandler('404')
def not_found(e):
    return 'Page not found', 404
D
@app.errorhandler(HTTPException)
def not_found(e):
    return 'Page not found', 404
Attempts:
2 left
💡 Hint

Check the type of argument @app.errorhandler expects for HTTP status codes.

🔧 Debug
advanced
2:00remaining
Why does this Flask app catch the custom exception in the route?

Given this Flask app code, the custom exception MyError raised in the route is caught by the error handler. Why?

Flask
from flask import Flask
app = Flask(__name__)

class MyError(Exception):
    pass

@app.route('/fail')
def fail():
    raise MyError('Oops')

@app.errorhandler(Exception)
def handle_exception(e):
    return 'Handled error', 500

# app.run() elsewhere
AThe error handler catches all exceptions, so it should catch MyError
BThe custom exception is not derived from Exception, so it is not caught
CThe error handler is registered after the route, so it is ignored
DFlask only catches HTTPException subclasses by default, so custom exceptions need explicit handling
Attempts:
2 left
💡 Hint

Consider Python inheritance and Flask's error handling behavior.

❓ state_output
advanced
2:00remaining
What is the response status code when a route raises an unhandled exception?

In this Flask app, the route raises a KeyError which has no registered error handler. What status code does the client receive?

Flask
from flask import Flask
app = Flask(__name__)

@app.route('/key')
def key_route():
    raise KeyError('missing key')

# No error handler for KeyError
# app.run() elsewhere
A500 Internal Server Error
B404 Not Found
C200 OK with empty body
D400 Bad Request
Attempts:
2 left
💡 Hint

Think about Flask's default behavior when exceptions are not handled.

🧠 Conceptual
expert
3:00remaining
How does Flask differentiate between HTTPException and other exceptions in error handling?

Flask has special handling for exceptions derived from werkzeug.exceptions.HTTPException. Which statement best describes this behavior?

AFlask converts all exceptions to HTTPException before handling
BHTTPException subclasses are ignored by Flask and always cause 500 errors
COnly exceptions not derived from HTTPException trigger error handlers
DHTTPException subclasses automatically generate HTTP responses with their code and description unless overridden
Attempts:
2 left
💡 Hint

Recall how Flask uses HTTPException to create HTTP error responses.

Practice

(1/5)
1. What is the main purpose of using @app.errorhandler in a Flask route?
easy
A. To connect to a database automatically
B. To define a new route in the Flask app
C. To catch specific errors and return custom responses
D. To start the Flask application server

Solution

  1. Step 1: Understand the role of @app.errorhandler

    This decorator is used to catch exceptions or errors that happen during request handling.
  2. Step 2: Purpose in routes

    It allows you to return a custom message or page instead of a default error, improving user experience.
  3. Final Answer:

    To catch specific errors and return custom responses -> Option C
  4. Quick Check:

    Error handling = catch and respond [OK]
Hint: Errorhandler decorates functions to catch errors in routes [OK]
Common Mistakes:
  • Confusing errorhandler with route decorator
  • Thinking it starts the server
  • Assuming it connects to databases
2. Which of the following is the correct syntax to handle a 404 error in Flask?
easy
A. @app.errorhandler(404) def not_found(error): return 'Page not found', 404
B. @app.route(404) def not_found(): return 'Page not found'
C. @app.errorhandler('404') def not_found(error): return 'Page not found', 404
D. @app.errorhandler(404) def not_found(): return 'Page not found'

Solution

  1. Step 1: Check the decorator usage

    The correct decorator is @app.errorhandler(404) with the status code as an integer.
  2. Step 2: Verify function signature and return

    The handler function should accept an error argument and return a response with the status code.
  3. Final Answer:

    @app.errorhandler(404)\ndef not_found(error):\n return 'Page not found', 404 -> Option A
  4. Quick Check:

    Correct decorator and function signature = A [OK]
Hint: Use integer status code and error parameter in handler [OK]
Common Mistakes:
  • Using @app.route instead of @app.errorhandler
  • Passing status code as string '404'
  • Missing error parameter in handler function
3. Given this Flask code snippet, what will be the output when accessing /divide/10/0?
from flask import Flask
app = Flask(__name__)

@app.route('/divide/<int:a>/<int:b>')
def divide(a, b):
    try:
        result = a / b
        return str(result)
    except ZeroDivisionError:
        return 'Cannot divide by zero', 400
medium
A. ZeroDivisionError exception traceback
B. 0
C. 10
D. Cannot divide by zero with HTTP status 400

Solution

  1. Step 1: Analyze the route and input

    The route divides a by b. Input is 10 and 0, so division by zero occurs.
  2. Step 2: Check exception handling

    The ZeroDivisionError is caught, returning 'Cannot divide by zero' with status 400.
  3. Final Answer:

    Cannot divide by zero with HTTP status 400 -> Option D
  4. Quick Check:

    ZeroDivisionError caught returns message and 400 [OK]
Hint: Try-except catches zero division, returns error message [OK]
Common Mistakes:
  • Expecting a crash or traceback
  • Ignoring the exception handling block
  • Assuming division returns 0
4. Identify the error in this Flask route error handling code:
@app.errorhandler(500)
def internal_error():
    return 'Internal Server Error', 500
medium
A. The handler function must accept an error parameter
B. The status code 500 is invalid for errorhandler
C. The return statement should not include status code
D. The decorator should be @app.route, not @app.errorhandler

Solution

  1. Step 1: Check function signature for errorhandler

    Functions decorated with @app.errorhandler must accept one parameter for the error.
  2. Step 2: Verify other parts

    Status code 500 is valid, return with status code is correct, and decorator usage is correct.
  3. Final Answer:

    The handler function must accept an error parameter -> Option A
  4. Quick Check:

    Errorhandler function needs error argument [OK]
Hint: Errorhandler functions always take an error argument [OK]
Common Mistakes:
  • Omitting the error parameter in handler function
  • Using wrong decorator for error handling
  • Returning without status code
5. You want to handle both 404 and 500 errors in your Flask app with custom JSON responses. Which approach correctly implements this?
hard
A. Use one function with @app.errorhandler([404, 500]) to handle both errors
B. Define two separate functions with @app.errorhandler(404) and @app.errorhandler(500), returning JSON and status codes
C. Handle errors inside each route function with try-except blocks only
D. Set app.config['ERROR_404_JSON'] = True and Flask will auto-handle JSON errors

Solution

  1. Step 1: Understand Flask errorhandler usage

    Flask requires separate functions for different error codes with their own decorators.
  2. Step 2: Confirm JSON response and status code

    Each handler should return a JSON response and the correct HTTP status code for clarity.
  3. Final Answer:

    Define two separate functions with @app.errorhandler(404) and @app.errorhandler(500), returning JSON and status codes -> Option B
  4. Quick Check:

    Separate handlers per error code = A [OK]
Hint: Use separate errorhandler functions for each error code [OK]
Common Mistakes:
  • Trying to handle multiple errors in one function decorator
  • Relying only on try-except inside routes
  • Assuming Flask auto-converts errors to JSON
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard