Understanding Error and Exception Handling in Python


Understanding Error and Exception Handling in Python

Errors and exceptions are inevitable in programming. Python provides a robust framework to handle them gracefully, ensuring your program can recover from unexpected conditions and continue running smoothly.


1. What are Errors and Exceptions?

  • Errors: Issues in the syntax or logic that prevent the program from running.
    Example: SyntaxError, IndentationError.
  • Exceptions: Errors detected during execution, which can be handled.
    Example: ValueError, ZeroDivisionError.

2. Common Types of Exceptions

Here are some frequently encountered exceptions in Python:

  1. SyntaxError: Occurs when there is an issue with the program’s syntax.
    Example: if True print("Hello") # SyntaxError: missing colon
  2. ZeroDivisionError: Occurs when dividing by zero.
    Example: print(10 / 0) # ZeroDivisionError
  3. ValueError: Raised when an operation receives an invalid argument.
    Example: int("abc") # ValueError: invalid literal for int()
  4. TypeError: Raised when an operation is performed on incompatible types.
    Example: "5" + 5 # TypeError: can't concatenate str and int
  5. KeyError: Raised when accessing a non-existent key in a dictionary.
    Example: data = {"name": "Alice"} print(data["age"]) # KeyError: 'age'

3. The try and except Block

The try and except block is used to catch and handle exceptions.

Basic Syntax:

try:
    # Code that might raise an exception
    risky_operation()
except ExceptionType:
    # Code to handle the exception
    handle_error()

Example:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print("Result:", result)
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("Invalid input. Please enter a number.")

4. The else and finally Clauses

  • else: Executes if no exception is raised in the try block.
  • finally: Executes regardless of whether an exception occurs, often used for cleanup.

Example:

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
else:
    print("File content:", content)
finally:
    file.close()
    print("File closed.")

5. Raising Exceptions

You can explicitly raise exceptions using the raise statement.

Example:

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or above.")
    print("Access granted.")

try:
    check_age(15)
except ValueError as e:
    print("Error:", e)

6. Creating Custom Exceptions

Python allows you to define custom exceptions for specific use cases.

Example:

class InvalidInputError(Exception):
    pass

def process_input(data):
    if not isinstance(data, int):
        raise InvalidInputError("Input must be an integer.")
    print("Processing:", data)

try:
    process_input("abc")
except InvalidInputError as e:
    print("Custom Exception:", e)

7. Best Practices for Exception Handling

  1. Be Specific with Exceptions: Catch only the exceptions you expect. # Bad practice: Catching all exceptions except Exception: pass
  2. Use finally for Cleanup: Always close files, release resources, or rollback transactions in the finally block.
  3. Avoid Silent Failures: Never suppress exceptions without logging or handling them. # Bad practice try: risky_operation() except Exception: pass # No action
  4. Log Errors: Use logging libraries to record errors for debugging.
  5. Rethrow Exceptions: If you can’t handle an exception, let it propagate. try: risky_operation() except SpecificError: raise

8. Real-World Use Case: API Request Handling

When working with external APIs, exception handling is crucial for dealing with issues like connection errors or invalid responses.

Example:

import requests

try:
    response = requests.get("https://api.example.com/data")
    response.raise_for_status()  # Raises HTTPError for bad responses
    data = response.json()
except requests.exceptions.RequestException as e:
    print("API request failed:", e)
else:
    print("Data received:", data)

Conclusion

Proper error and exception handling is a hallmark of robust and professional code. By anticipating and managing exceptions effectively, you can ensure your Python applications are reliable and user-friendly.

How to Handle git pull with Local Changes on AWS

When working with Git on an AWS environment, you might encounter a situation where you need to pull updates from your remote repository, but you also have uncommitted local changes. This tutorial will guide you through three scenarios to handle this situation effectivel


Scenario 1: Keeping Your Local Changes

If your local changes are important and need to be preserved, follow these steps:

1. Stage Your Changes

Use git add to stage all your local changes:

git add .

2. Commit Your Changes

Commit the staged changes with a meaningful message:

git commit -m "Describe your local changes here"

3. Pull Updates from Remote

After committing, pull the latest changes from your remote repository:

git pull origin main

If there are conflicts, Git will notify you. Resolve conflicts manually, then continue with:

git add .
git commit -m "Resolve merge conflicts"

4. Push Your Changes

Once resolved, push the combined changes to the remote repository:

git push origin main

Scenario 2: Discarding Your Local Changes

If your local changes are unnecessary and can be discarded, follow these steps:

1. Discard Unstaged Changes

To discard changes that haven’t been staged:

git restore .

2. Unstage Any Staged Changes

If any changes were staged with git add, unstage them:

git reset
git restore .

3. Pull Updates from Remote

Now, safely pull the latest changes:

git pull origin main

Scenario 3: Temporarily Saving Your Local Changes

If you’re unsure about keeping or discarding your changes, you can stash them temporarily:

1. Stash Your Changes

Stash your local changes to save them temporarily:

git stash

2. Pull Updates from Remote

Pull the latest changes after stashing:

git pull origin main

3. Apply Stashed Changes

Reapply your saved changes from the stash:

git stash apply

Tips for Best Practices

  1. Use a .gitignore File
    To avoid unnecessary files like .pyc or build files from being tracked, always set up a .gitignore file in your repository. Example .gitignore: *.pyc node_modules/ .env
  2. Test Changes Locally
    Before pushing local changes, test them thoroughly in your AWS environment.
  3. Communicate with Your Team
    If working in a team, communicate about your changes to avoid conflicts during git pull.

Conclusion

Managing local changes while pulling updates from a Git repository is a common scenario for developers working on AWS or any remote server. By following the steps in this guide, you can handle local changes confidently and avoid issues like merge conflicts.

Feel free to share your experiences or questions in the comments below!


How to fetch REST API data in React

In this tutorial, we will learn how to fetch REST API data and use it in react components by building a book catalogue page.Setting up a React app

Execute the following commands to set up a React app: $ npx create-react-app my_cool_app $ cd my_cool_app $ npm start

Copy the following code to /src/index.js

import React from 'react'; import ReactDOM from 'react-dom/client'; function MyApp() { return <h1> Books Available </h1>; } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<MyApp />);

Check the app at http://127.0.0.1:3000/

Building an user interface for book catalogue.

Modify the MyApp function to show some demo books:

function MyApp() { const demo_books = [ { "id": -1, "name": "Book-Name", "author": "Author-Name" }]; const books = demo_books; // TODO: add useState() here. const content = books.map( p => { return ( <li key={p.id}> <b> { p.name } </b> by <i> { p.author } </i> </li> ) }); return ( <div> <h1> Books Available </h1> <ul> { content } </ul> </div> ); }

Make the books variable the component’s state.

Replace the books variable initialization line with the following useState code.

// Need: import { useState } from 'react'; const [books, setBooks] = useState(demo_books)

Creating a REST API URL

Create a file book.json inside the /public directory. Add the following content to the file.


[
    {
        "id": 1,
        "name": "Code Complete",
        "author": "Steve McConnell"
    },
    {
        "id": 2,
        "name": "The Pragmatic Programmer",
        "author": "Andrew Hunt"
    },
    {
        "id": 3,
        "name": "Programming Pearls",
        "author": "Jon L. Bentley"
    }
]

You can access the books.json at http://127.0.0.1:3000/books.json

Use fetch api to retrieve REST API data.

Add the following fetch api code after the useState() code.

// Need: import { useEffect } from 'react'; useEffect(() => { fetch('/books.json') .then(response => response.json()) .then(setBooks); }, []); // empty-brackets to fetch data only once.

MyApp will get executed every time the state of the component changes. useEffect with zero-dependency will fetch the data only once. If you don’t use useEffect, the change of the books-state by fetch api will invoke the MyApp function, which contains the fetch api code. This cycle will retrieve the REST data an indefinite number of times.

If you define another state which influences the data (say total_books) , you should use the second argument to specify it so that the data will be fetched every time that state changes:  useEffect( _ , [total_books]); 

Your app will show the following output:

 

Books Available
  • Code Complete by Steve McConnell
  • The Pragmatic Programmer by Andrew Hunt
  • Programming Pearls by Jon L. Bentley

 

Here goes the complete code:

import React from 'react'; import ReactDOM from 'react-dom/client'; import { useState, useEffect } from 'react'; function MyApp() { const [books, setBooks] = useState([]) useEffect(() => { fetch('/books.json') .then(response => response.json()) .then(setBooks); }, []); const content = books.map( p => { return ( <li key={p.id}> <b> { p.name } </b> by <i> { p.author } </i> </li> ) }); return ( <div> <h1> Books Available </h1> <ul> { content } </ul> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<MyApp />);

 


Thanks for coming by 🙂


WhatsApp forward Message Wp20.ru link, is it trustworthy to click ?

No of course not , Last week onward wp20.ru link message are circulating on WhatsApp. You might get this message from friends / family circle, please don’t click it it is a virus link.It install automatically virus to you browser.unfortunately any of your trusted fried shared that Wp20.ru and you already opened that website please clear cache & cookies .if you dont know how to do that please follow this link https://support.google.com/accounts/answer/32050?hl=en&co=GENIE.Platform%3DAndroid&oco=1 and don’t forgot to restart your system after clearing cache & cookies

Almost all different antivirus vendors listed this link as Malware/Phishing/ Suspicious link. So stay away from this link, If you see a link starting with wp20.ru don’t click it..

WhatsApp forward Message Wp20.ru link