PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label try-catch. Show all posts
Showing posts with label try-catch. Show all posts

Sunday, December 18, 2022

[FIXED] Why do try blocks need a catch

 December 18, 2022     c#, catch-block, syntax, try-catch     No comments   

Issue

I have this code :

try 
{
    result.FirstName = nodes[myIdx]
        .Attributes["ows_FirstName"].Value;
} 
catch { }

Now I don't know prior to invoking this call if the attribute I am looking for exists (Good ol sharepoint).

As a result the only linear way I can write the code I am looking to create is as such.

try 
{
    result.FirstName = nodes[myIdx]
        .Attributes["ows_FirstName"]
        .Value;
} 
catch { }

try 
{
    result.LastName = nodes[myIdx]
        .Attributes["ows_LastName"]
        .Value;
} 
catch { }

Now I have no use for the catch section of this code and end up with a huge amount of lines that are completely redundant.

Why couldn't I just do

try 
{
    result.FirstName = nodes[myIdx]
        .Attributes["ows_FirstName"]
        .Value;
}

So why are we explicitly forced to declare a catch block even when it isn't handled? I'm sure there is a good reason but can't work it out.

I know the importance of exception handling, but here is simply nothing exceptional about the exception and nothing I can do (nor need to do) to fix the behavior.


Solution

They are not redundant - they have a specific purpose. By default the lack of a catch block will re-throw the exception to the calling method. An empty catch block essentially "swallows" the exception and lets the program continue, oblivious to whether or not an exception was thrown; generally a bad practice.

there is simply nothing exceptional about the exception

it may be true that one type of exception may not be "exceptional" in this case, but that's not the only exception that can occur. You should handle that exception and deal with any others appropriately.

For example -

What if nodes is null? What if myIdx is outside the bounds of the nodes array? Either of these conditions would be exceptional and you should either handle them specifically or let the calling program handle them and act appropriately.

[there's] nothing I can do (or need to do) to fix the behaviour

You may not be able to fix it, but you may need to be aware of it. How does the program behave differently in that case? Log a message? Raise a warning? Set a default value? Do nothing may be an appropriate answer, but very likely not an appropriate response to any possible exception.



Answered By - D Stanley
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 14, 2022

[FIXED] How do I save warnings and errors as output from a function?

 November 14, 2022     error-handling, r, try-catch     No comments   

Issue

I'm using lapply to run a complex function on a large number of items, and I'd like to save the output from each item (if any) together with any warnings/errors that were produced so that I can tell which item produced which warning/error.

I found a way to catch warnings using withCallingHandlers (described here). However, I need to catch errors as well. I can do it by wrapping it in a tryCatch (as in the code below), but is there a better way to do it?

catchToList <- function(expr) {
  val <- NULL
  myWarnings <- NULL
  wHandler <- function(w) {
    myWarnings <<- c(myWarnings, w$message)
    invokeRestart("muffleWarning")
  }
  myError <- NULL
  eHandler <- function(e) {
    myError <<- e$message
    NULL
  }
  val <- tryCatch(withCallingHandlers(expr, warning = wHandler), error = eHandler)
  list(value = val, warnings = myWarnings, error=myError)
} 

Sample output of this function is:

> catchToList({warning("warning 1");warning("warning 2");1})
$value
[1] 1

$warnings
[1] "warning 1" "warning 2"

$error
NULL

> catchToList({warning("my warning");stop("my error")})
$value
NULL

$warnings
[1] "my warning"

$error
[1] "my error"

There are several questions here on SO that discuss tryCatch and error handling, but none that I found that address this particular issue. See How can I check whether a function call results in a warning?, warnings() does not work within a function? How can one work around this?, and How to tell lapply to ignore an error and process the next thing in the list? for the most relevant ones.


Solution

Maybe this is the same as your solution, but I wrote a factory to convert plain old functions into functions that capture their values, errors, and warnings, so I can

test <- function(i)
    switch(i, "1"=stop("oops"), "2"={ warning("hmm"); i }, i)
res <- lapply(1:3, factory(test))

with each element of the result containing the value, error, and / or warnings. This would work with user functions, system functions, or anonymous functions (factory(function(i) ...)). Here's the factory

factory <- function(fun)
    function(...) {
        warn <- err <- NULL
        res <- withCallingHandlers(
            tryCatch(fun(...), error=function(e) {
                err <<- conditionMessage(e)
                NULL
            }), warning=function(w) {
                warn <<- append(warn, conditionMessage(w))
                invokeRestart("muffleWarning")
            })
        list(res, warn=warn, err=err)
    }

and some helpers for dealing with the result list

.has <- function(x, what)
    !sapply(lapply(x, "[[", what), is.null)
hasWarning <- function(x) .has(x, "warn")
hasError <- function(x) .has(x, "err")
isClean <- function(x) !(hasError(x) | hasWarning(x))
value <- function(x) sapply(x, "[[", 1)
cleanv <- function(x) sapply(x[isClean(x)], "[[", 1)


Answered By - Martin Morgan
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is Try Block of code not counting the same as when I don't use Try?

 November 14, 2022     api, error-handling, list, python, try-catch     No comments   

Issue

I have a function that pulls data from a Restaurant's Clover POS System, then returns dictionaries with how many of each item was sold and then how many of each modification was made (ex: "Remove Nutella":5)

My problem occurs when one of the orders in the data didn't actually have an item on it.

So I wrapped a try statement around my for loop in case there's is a blank check open. However it changes the total values that my function returns.

So here is my code with the try statement in line 5(This is the one of concern):

        for index in range(len(data_elements)):
            order = data_elements[index]
            print(index)
            
            try:
                for i in range(len(order["lineItems"]["elements"])):
                    item = order["lineItems"]["elements"][i]["name"]
                    item = item.replace(" TPD","")
                    item = item.replace("*","")
                    item = item.replace("Bowl ","Bowl")

                    if item in inventory_sold:
                        inventory_sold[item] += 1
                    else:
                        inventory_sold[item] = 1
                try:
                    for ind in range(len(order["lineItems"]["elements"][i]["modifications"]["elements"])):
                        item_modification = order["lineItems"]["elements"][i]["modifications"]["elements"][ind]["name"]
                        item_modification = item_modification.replace("(or Extra) ","")
                        item_modification=item_modification.replace("or Extra ","")
                        item_modification=item_modification.replace("Strawberries","Strawberry")
                        item_modification=item_modification.replace("Substitute","Sub")
                        item_modification = item_modification.strip()

                        if item_modification in mod_dict:
                            mod_dict[item_modification] += 1
                        else:
                            mod_dict[item_modification] = 1
                except KeyError:
                    pass
            except KeyError:
                pass

        return [inventory_sold,mod_dict]

So for example yesterday there were no blank checks left open so my code runs smooth without the try statement however I need to account for days where there may be a check with no item on it.

Without the try statement in line 5 my code looks like this:

        for index in range(len(data_elements)):
            order = data_elements[index]
            print(index)

            
            for i in range(len(order["lineItems"]["elements"])):
                item = order["lineItems"]["elements"][i]["name"]
                item = item.replace(" TPD","")
                item = item.replace("*","")
                item = item.replace("Bowl ","Bowl")

                if item in inventory_sold:
                    inventory_sold[item] += 1
                else:
                    inventory_sold[item] = 1
                try:
                    for ind in range(len(order["lineItems"]["elements"][i]["modifications"]["elements"])):
                        item_modification = order["lineItems"]["elements"][i]["modifications"]["elements"][ind]["name"]
                        item_modification = item_modification.replace("(or Extra) ","")
                        item_modification=item_modification.replace("or Extra ","")
                        item_modification=item_modification.replace("Strawberries","Strawberry")
                        item_modification=item_modification.replace("Substitute","Sub")
                        item_modification = item_modification.strip()

                        if item_modification in mod_dict:
                            mod_dict[item_modification] += 1
                        else:
                            mod_dict[item_modification] = 1
                except KeyError:
                    pass
            

        return [inventory_sold,mod_dict]

This above code correctly counts the values from my data for example ("Add Nutella": 38)

Meanwhile when I add the try statement in line 5 from earlier to account for days that there may be a KeyError my values are short. Ex.("Add Nutella" :26)

Also I should add the first dictionary is correct no matter what for some reason the 3rd for loop which creates the mods dictionary is the one that gets affected.

Any help is much appreciated!


Solution

From our discussion it seems that your problem is that there may sometimes not be elements when looping through. Therefore you could likely do something like this instead of try except blocks. (some of your code was refactored for readability purposes)

for index,order in enumerate(data_elements): # enumerate allows you to access both the index and the element
    print(index)
    
    if 'lineItems' not in order: # check if there are lineItems in the order
        continue # continues the for loop (skipping the below)
    
    for order_item in order["lineItems"]["elements"]: # access the elements directly
        order_name = order_item["name"]
        order_name = order_name.replace(" TPD","")
        order_name = order_name.replace("*","")
        order_name = order_name.replace("Bowl ","Bowl")

        if order_name in inventory_sold:
            inventory_sold[order_name] += 1
        else:
            inventory_sold[order_name] = 1

        if 'modifications' not in order_item: # check if there are modifications in the order
            continue # continues the for loop (skipping the below)
        
        for order_modification in order_item["modifications"]["elements"]:
            order_modification_name = order_modification["name"]
            order_modification_name = order_modification_name.replace("(or Extra) ","")
            order_modification_name = order_modification_name.replace("or Extra ","")
            order_modification_name = order_modification_name.replace("Strawberries","Strawberry")
            order_modification_name = order_modification_name.replace("Substitute","Sub")
            order_modification_name = order_modification_name.strip()

            if order_modification_name in mod_dict:
                mod_dict[order_modification_name] += 1
            else:
                mod_dict[order_modification_name] = 1

return [inventory_sold,mod_dict]

Using if statements to catch any errors that may occur and handle the code appropriately as they are known elements to occur.



Answered By - Andrew Ryan
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How To Get Exit Code From PowerShell Script

 November 14, 2022     error-handling, exit-code, powershell, try-catch     No comments   

Issue

I'm trying to write a PowerShell script which sends a Slack notification whenever our build system in unable to push Docker images to Docker Hub. How can I detect and handle the Process exited with code 1 from the docker push command? I've tried the following, but the catch block isn't called.

try {
  docker push $dockerImage;
}catch{
  #Send error details to Slack
}

Solution

  • As of PowerShell 7.3, calls to external programs (such as docker) never cause a statement-terminating error[1] that you can trap with try / catch; similarly, stderr output from external program is (rightfully) not considered error output by PowerShell, and therefore $ErrorActionPreference = 'Stop' has no effect on it (for legacy exceptions in Windows PowerShell, see this answer).

    • However, opt-in integration with PowerShell's error handling may be implemented in the future; as of v7.3, there is an experimental feature named PSNativeCommandErrorActionPreference (which may become an official feature):

      • If this feature is enabled (Enable-ExperimentalFeature PSNativeCommandErrorActionPreference) and the associated $PSNativeCommandErrorActionPreference preference variable is set to $true, any external-program call that reports a nonzero exit code automatically triggers a PowerShell error in response (obviating the need for explicit $LASTEXITCODE -ne 0 checks), which then integrates with PowerShell's own error handling.[2]
    • In general, note that a statement-terminating PowerShell error (which can be caught with try / catch) does occur if PowerShell fails to even launch a command, such as when you supply a non-existent executable name or path; e.g.:

      try   { nosuchexe foo bar }
      catch { Write-Warning "Failed to invoke nosuchexe: $_" }
      
  • The automatic $LASTEXITCODE variable reflects the process exit code of the most recently executed external program. By convention, exit code 0 signals success, anything else an error condition.

Therefore:

docker push $dockerImage
if ($LASTEXITCODE -ne 0) {
  #Send error details to Slack
}

See also:

  • This answer has more information on exit-code processing in PowerShell.

[1] The only exception is a bug, present up to PowerShell 7.1, where the combination of redirecting stderr output (2> or *>) with $ErrorActionPreference = 'Stop' unexpectedly causes a script-terminating error if there's actual stderr output - see this answer.

[2] Unfortunately, as of v7.3.0, the automatically triggered PowerShell error is a non-terminating error rather than a statement-terminating one; the latter would make more sense, as it would allow it to be selectively caught with a try statement - see GitHub issue #18368.



Answered By - mklement0
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What are the differences between throws and rethrows in Swift?

 November 14, 2022     error-handling, rethrow, swift, throws, try-catch     No comments   

Issue

After searching for some references to figure it out, -unfortunately- I could not find useful -and simple- description about understanding the differences between throws and rethrows. It is kind of confusing when try to understand how we should use them.

I would mention that I am kind of familiar with the -default- throws with its simplest form for propagating an error, as follows:

enum CustomError: Error {
    case potato
    case tomato
}

func throwCustomError(_ string: String) throws {
    if string.lowercased().trimmingCharacters(in: .whitespaces) == "potato" {
        throw CustomError.potato
    }

    if string.lowercased().trimmingCharacters(in: .whitespaces) == "tomato" {
        throw CustomError.tomato
    }
}

do {
    try throwCustomError("potato")
} catch let error as CustomError {
    switch error {
    case .potato:
        print("potatos catched") // potatos catched
    case .tomato:
        print("tomato catched")
    }
}

So far so good, but the problem arises when:

func throwCustomError(function:(String) throws -> ()) throws {
    try function("throws string")
}

func rethrowCustomError(function:(String) throws -> ()) rethrows {
    try function("rethrows string")
}

rethrowCustomError { string in
    print(string) // rethrows string
}

try throwCustomError { string in
    print(string) // throws string
}

what I know so far is when calling a function that throws it has to be handled by a try, unlike the rethrows. So what?! What is logic that we should follow when deciding to use throws or rethrows?


Solution

From "Declarations" in the Swift book:

Rethrowing Functions and Methods

A function or method can be declared with the rethrows keyword to indicate that it throws an error only if one of its function parameters throws an error. These functions and methods are known as rethrowing functions and rethrowing methods. Rethrowing functions and methods must have at least one throwing function parameter.

A typical example is the map method:

public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

If map is called with a non-throwing transform, it does not throw an error itself and can be called without try:

// Example 1:

let a = [1, 2, 3]

func f1(n: Int) -> Int {
    return n * n
}

let a1 = a.map(f1)

But if map is called with a throwing closure then itself can throw and must be called with try:

// Example 2:

let a = [1, 2, 3]
enum CustomError: Error {
    case illegalArgument
}

func f2(n: Int) throws -> Int {
    guard n >= 0 else {
        throw CustomError.illegalArgument
    }
    return n*n
}


do {
    let a2 = try a.map(f2)
} catch {
    // ...
}
  • If map were declared as throws instead of rethrows then you would have to call it with try even in example 1, which is "inconvenient" and bloats the code unnecessary.
  • If map were declared without throws/rethrows then you could not call it with a throwing closure as in example 2.

The same is true for other methods from the Swift Standard Library which take function parameters: filter(), index(where:), forEach() and many many more.

In your case,

func throwCustomError(function:(String) throws -> ()) throws

denotes a function which can throw an error, even if called with a non-throwing argument, whereas

func rethrowCustomError(function:(String) throws -> ()) rethrows

denotes a function which throws an error only if called with a throwing argument.

Roughly speaking, rethrows is for functions which do not throw errors "on their own", but only "forward" errors from their function parameters.



Answered By - Martin R
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 14, 2022

[FIXED] How to manage axios errors globally or from one point

 October 14, 2022     axios, javascript, promise, try-catch, vuejs2     No comments   

Issue

I have the standard then/catch axios code all over my app, a simple one goes likes this..

axios.get('/').then( r => {} ).catch( e => {} )

The problem I have with the above is that I have to duplicate the catch() block to handle any potential errors that my be invoked in my app and my questions is, if there is anything I can do to catch the errors globally from on entry point as opposed to using catch everywhere.

I am looking for solutions from either axios side or vue, since my app is built with vue


Solution

You should use an interceptor.

First, create an axios instance using the create method. This is what you would need to use throughout your app instead of referencing axios directly. It would look something like this:

let api = axios.create({
  baseURL: 'https://example.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Then attach an interceptor to your axios instance to be called after the response to each of the requests for that instance:

api.interceptors.response.use((response) => response, (error) => {
  // whatever you want to do with the error
  throw error;
});


Answered By - thanksd
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access Axios error response object in catch clause?

 October 14, 2022     axios, reactjs, try-catch, typescript     No comments   

Issue

I recently upgraded to axios 0.23.0 and I am now receiving an error when trying to access the error response object in a catch clause. This is where I am getting the error:

  const loginUser = async (userData: UserPayload): Promise<void> => {
    try {
      const result = await login(userData);
      const { token } = result.data;
      localStorage.setItem('jwtTokenTS', token);
      setupAxios(token);
      const decoded: User = jwt_decode(token);
      setUser(decoded);
      setAuthenticated(true);
    } catch (err) {
      if (err.response.status === 404) {
        window.alert('User not found');
      } else if (err.response.status === 401) {
        window.alert('Incorrect password');
      } else {
        console.error(err);
      }
    }
  };

The "login" function on line 3 is my axios request as seen below:

export async function login(user: UserPayload): Promise<AxiosResponse<{ token: string }>> {
  return axios.post(`${bConfig.backend}/login`, user);
}

The exact error I receive is when trying to access "err.response.status":

Object is of type 'unknown'.ts(2571) (local var) err: unknown

Any ideas on how to get rid of this error will be appreciated, I have tried typing the error at the catch clause but typescript doesn't like this either.


Solution

Update: As mentioned by @matas-ramanauskas in another answer, a built-in type guard available from Axios (see https://github.com/axios/axios/pull/3546/files). The built in type guard should be able to handle also when the object being checked is null since error.isAxiosError will return an error is error is null.

I've also updated the code below to check whether error is not null or not undefined before checking the isAxiosError property.


Since TypeScript 4.4, catch clause variables are now defaulted from any to unknown type unless configured not to. This allows for safer handling as it forces users to check the type of caught value in the catch clause before being used. To get rid of that error, you need to use a type guard to narrow down the possible types of the object to let TypeScript know what type it is dealing with.

You can do something like this:

const isAxiosError = (error: unknown): error is AxiosError => {
  return error && (error as AxiosError).isAxiosError;
};

try {
  // ...
} catch (err) {
  if (isAxiosError(err) && err.response) {
    if (err.response.status === 404) {
      window.alert('User not found');
    } else if (err.response.status === 401) {
      window.alert('Incorrect password');
    } else {
      console.error(err);
    }
  } else {
    console.error(err);
  }
}

You can check out the guide I made specifically for this scenarios. https://www.linkedin.com/posts/michael-bonon_handling-typed-errors-in-typescript-44-activity-6865161464236400640-MkWB



Answered By - Michael Boñon
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] How can I make it so that a value becomes "NULL" if there's an Exception?

 August 05, 2022     exception, loops, python, try-catch     No comments   

Issue

I'm storing data from an API (that I then store as a pickle) and sometimes there are errors due to missing fields. I'm wondering how I can make it so that it only targets the problematic variable and logs its value as "NULL".

The issue is that I'm storing 6 different variables, so if a single one of them has an issue, all other 5 variables will be skipped. Instead, I want that (or those) problematic variables get replaced by the value "NULL" (or None).

meta = loaded_from_pickle('myData.pickle')

def getAllData():

    data = []
    for i in range(len(meta)):
        try:
            name = meta[i]['base']['name']
            weight = meta[i]['base']['weight']
            height = meta[i]['base']['height']

            age = meta[i]['secondary']['age']
            eye_color = meta[i]['secondary']['eye_color']
            birthday = meta[i]['secondary']['birthday']

            data.append((name, weight, height, age, eye_color, birthday))

        except:
            pass

    return data

print(getAllData())

So what happens is that I end up losing a lot of data points because some data doesn't have "eye_color" or whatnot. So what I should do when there's an "except" should be "make problematic variable = "NULL" ", rather than just passing the entire loop.


Solution

Instead of accessing the keys directly using square brackets try using get() it returns a default value of None if the key is not found.

See this answer for more info https://stackoverflow.com/a/11041421/3125312

You could use it in your code:

name = meta[i]['base'].get('name')
weight = meta[i]['base'].get('weight')
height = meta[i]['base'].get('height')
...

You could also rewrite your for loop using enumerate assuming meta is a list

for index, value in enumerate(meta):
    name = value['base'].get('name')
    ...


Answered By - Siddharth
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use TryCatch Statement in ToDictionary C#?

 August 05, 2022     c#, exception, linq, try-catch     No comments   

Issue

I have a dictionary of asyncronous call . The problem is sometimes these asyncronous call will throw an exception but I am not entirely sure how to handle them . The GetUserLicenseTypes returns a list so if I do get an exception I still want to return an empty list.

var tasks = allCompanyUsers.ToDictionary(
                u => u.Id,
                u => _subscriptionService.GetUserSubscription(companyId, u.Id));

            await Task.WhenAll(tasks.Values);

            var licenseListByUserId = tasks.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Result);

The code below doesn't work but I wanted to do something like this

var tasks = allCompanyUsers.ToDictionary(
                u => u.Id,
                u => {
try{
     return _subscriptionService.GetUserSubscription(companyId, u.Id);
}catch{
     return new List<string>();
}
});

            await Task.WhenAll(tasks.Values);

            var licenseListByUserId = tasks.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Result);

Note : I have gotten feedback that I should just avoid exception all together but at the moment it is hard to do considering that the GetUserSubscription function is already used in many location so the typical convention our application use is a trycatch statement to handle these thrown error.


Solution

Here's one way:

async Task<IEnumerable<string>> GetSubscriptions(Guid userId)
{
    try { return await _subscriptionService.GetUserSubscription(companyId, userId); }
    catch { return new List<string>(); }
}

var idsWithSubscriptions = await Task.WhenAll(allCompanyUsers
    .Select(async u => (
        u.Id,
        Subscription: await GetSubscriptions(u.Id))));

var licenseListByUserId = idsWithSubscriptions.ToDictionary(
    iws => iws.Id,
    iws => iws.Subscription);

Because the Task returned from GetUserSubscription is awaited, it will unwrap and throw any Exception, meaning the value in the catch block will be returned.



Answered By - Johnathan Barclay
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I make catching exceptions assign a variable a certain value without constantly repeating the code?

 August 05, 2022     exception, python, try-catch     No comments   

Issue

I'm going to clarify.

I'm logging 6 different variables and some of them have errors (what kind of error doesn't matter). When that error occurs, I just want that specific variable to be put to "NA".

Here's an idea of what I mean:

myDict = []
for i in data:
    try:
        eye = ...
        nose = ...
        mouth = ...
        ear = ...
        hair = ...
        tongue = ...
        
        myDict.append([eye, nose, mouth, ear, hair, tongue])

   except eye:
        eye = "NA"
        myDict.append([eye, nose, mouth, ear, hair, tongue])
  
   except nose:
        nose = "NA"
        myDict.append([eye, nose, mouth, ear, hair, tongue])

   except mouth:
        mouth = "NA"
        myDict.append([eye, nose, mouth, ear, hair, tongue])

   ...

Do I have to do an "except" for every single variable? Is there some way I could just do "except whatever variable has error, assign its value to "NA" and append normally"?

I also don't know what happens if there's an error in more than 1 variable.

The fundamental idea is: "if there's an error for a variable(S), just assign it/them the value "NA" and keep appending.


Solution

Here's an example of an approach that will do what you're asking.

First some comments:

  • You have used the term "error", but your sample code uses try/except, so I will assume that each "error" results in an exception being raised.
  • In the code below, I use an artificially simplified scenario in which the assignment to each variable has the possibility of raising an exception with a similar name, and I have created these as user-defined exceptions; in reality, you may not need to define these and would instead replace the parenthesized exception types in the sample code with the actual exceptions that you want to catch.
  • You have something called myDict which is actually a python list; I will rename this result in the code below to avoid confusion.

The logic of the code below can be summarized as:

  • Instead of assigning directly to named variables (as in the code in your question), iterate through a list of variable tags (strings like 'eye', 'nose', etc.) in an inner loop which has a try/except block inside it;
  • Within this inner list, do the work for the given tag (the same work that would be done by eye = ... or mouth = ... in your question) and append the result to a list L, unless an exception is raised, in which case the try block instead appends "NA" to L;
  • This means that whether or not there are errors (more accurately, whether or not exceptions are raised), L will have a value appended to it for each variable tag;
  • At the end of the inner loop, append L to the result.

Here is the sample code:

class eye_exception(Exception):
    pass
class nose_exception(Exception):
    pass
class mouth_exception(Exception):
    pass
class ear_exception(Exception):
    pass
class hair_exception(Exception):
    pass
class tongue_exception(Exception):
    pass


def getValueForEye(i):
    return "eye_value" + str(i)
def getValueForNose(i):
    return "nose_value" + str(i)
def getValueForMouth(i):
    if i % 3 == 0:
        raise mouth_exception()
    return "mouth_value" + str(i)
def getValueForEar(i):
    return "ear_value" + str(i)
def getValueForHair(i):
    if i % 3 != 0:
        raise hair_exception()
    return "hair_value" + str(i)
def getValueForTongue(i):
    return "tongue_value" + str(i)

data = [1, 2, 3]

result = []
for i in data:
    L = []
    for key in ['eye', 'nose', 'mouth', 'ear', 'hair', 'tongue']: 
        try:
            match key:
                case 'eye':
                     value = getValueForEye(i)
                case 'nose':
                     value = getValueForNose(i)
                case 'mouth':
                     value = getValueForMouth(i)
                case 'ear':
                     value = getValueForEar(i)
                case 'hair':
                     value = getValueForHair(i)
                case 'tongue':
                     value = getValueForTongue(i)
            L.append(value)
        except (eye_exception, nose_exception, mouth_exception, ear_exception, hair_exception, tongue_exception):
            L.append("NA")
    result.append(L)

Sample result:

['eye_value1', 'nose_value1', 'mouth_value1', 'ear_value1', 'NA', 'tongue_value1']
['eye_value2', 'nose_value2', 'mouth_value2', 'ear_value2', 'NA', 'tongue_value2']
['eye_value3', 'nose_value3', 'NA', 'ear_value3', 'hair_value3', 'tongue_value3']

Alternatively, if you are using a version of python that does not support the match/case construct, or you simply prefer not to use it, you can replace the loop above with this code which uses a dictionary to map from variable tag to function:

funcDict = {
    'eye':getValueForEye, 
    'nose':getValueForNose, 
    'mouth':getValueForMouth, 
    'ear':getValueForEar, 
    'hair':getValueForHair, 
    'tongue':getValueForTongue
}
for i in data:
    L = []
    for key, func in funcDict.items(): 
        try:
            value = func(i)
            L.append(value)
        except (eye_exception, nose_exception, mouth_exception, ear_exception, hair_exception, tongue_exception):
            L.append("NA")
    result.append(L)


Answered By - constantstranger
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to return a value from try, catch, and finally by using condition?

 August 05, 2022     conditional-statements, exception, java, return-value, try-catch     No comments   

Issue

My get() method is being marked with a red line, it tells me

this method must return a result of type char

public char get() {
    mutex.lock();
    char c = buffer[out];
    try {
        while (count == 0) {  
            okConsume.await();
        }
        out = (out + 1) % buffer.length;
        count--;
        System.out.println("Consuming " + c + " ...");
        okConsume.signalAll();
        return c;
    }catch(InterruptedException ie) {
        ie.printStackTrace();
    }finally {
        mutex.unlock();
    }
    
}

Solution

Your code should cover all the possible scenario. Now it doesn't because you're not returning from the method if exception occur.

The return statement placed inside the try will be unreachable in case of exception.

For more information on Exception-handling, I suggest to have a look at this tutorial.

There are two ways to fix it:

  • place return statements in both try and catch blocks;
    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            // some code
            return c;
        } catch (InterruptedException ie) {
            ie.printStackTrace();
            return c;
        } finally {
            mutex.unlock();
        }
    }
  • place the return statement after the finally block;
    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            // some code
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } finally {
            mutex.unlock();
        }
        return c;
    }


Answered By - Alexander Ivanchenko
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 4, 2022

[FIXED] How to catch and print the full exception traceback without halting/exiting the program?

 August 04, 2022     exception, python, traceback, try-catch     No comments   

Issue

I want to catch and log exceptions without exiting, e.g.,

try:
    do_stuff()
except Exception as err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details

I want to print the exact same output that is printed when the exception is raised without the try/except intercepting the exception, and I do not want it to exit my program.


Solution

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")


Answered By - Sylvain Leroux
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is Boolean.valueOf(String) returning false when given neither true or false but a random String?

 August 04, 2022     boolean, exception, java, try-catch     No comments   

Issue

When using the method Boolean.valueOf(String) the return value is false when given any String besides "true". This try block neverseems to fail even if it should?

boolean a;

String b = "randomTextThatsNotTrueOrFalse";

try{
a= Boolean.valueOf(b);
} 
catch(IllegalArgumentException e) {

 LOG.error(b  + "is invalid. Only true or false are possible  Options.");

}

Solution

As per the spec (and, as expected, the source code of the OpenJDK implementation follows this spec), "true" (with any casing) is parsed as true, and all other strings are parsed as false:

   * Returns a {@code Boolean} with a value represented by the
   * specified string.  The {@code Boolean} returned represents a
   * true value if the string argument is not {@code null}
   * and is equal, ignoring case, to the string {@code "true"}.
   * Otherwise, a false value is returned, including for a null
   * argument.

Reading javadoc is important; you should make a habit of it.

If you want a method that returns true if passed "true", false if passed "false", and throws an IAEx otherwise, you'd have to write it yourself. It's about 80 characters worth of code.



Answered By - rzwitserloot
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get the last exception object after an error is raised at a Python prompt?

 August 04, 2022     exception, python, read-eval-print-loop, try-catch     No comments   

Issue

When debugging Python code at the interactive prompt (REPL), often I'll write some code which raises an exception, but I haven't wrapped it in a try/except, so once the error is raised, I've forever lost the exception object.

Often the traceback and error message Python prints out isn't enough. For example, when fetching a URL, the server might return a 40x error, and you need the content of the response via error.read() ... but you haven't got the error object anymore. For example:

>>> import urllib2
>>> f = urllib2.urlopen('http://example.com/api/?foo=bad-query-string')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
urllib2.HTTPError: HTTP Error 400: Bad Request

Drat, what did the body of the response say? It probably had valuable error information in it...

I realize it's usually easy to re-run your code wrapped in a try/except, but that's not ideal. I also realize that in this specific case if I were using the requests library (which doesn't raise for HTTP errors), I wouldn't have this problem ... but I'm really wondering if there's a more general way to get the last exception object at a Python prompt in these cases.


Solution

The sys module provides some functions for post-hoc examining of exceptions: sys.last_type, sys.last_value, and sys.last_traceback.

sys.last_value is the one you're looking for.



Answered By - Cairnarvon
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you implement a re-try-catch?

 August 04, 2022     exception, exception-handling, java, try-catch     No comments   

Issue

Try-catch is meant to help in the exception handling. This means somehow that it will help our system to be more robust: try to recover from an unexpected event.

We suspect something might happen when executing and instruction (sending a message), so it gets enclosed in the try. If that something nearly unexpected happens, we can do something: we write the catch. I don't think we called to just log the exception. I thing the catch block is meant to give us the opportunity of recovering from the error.

Now, let's say we recover from the error because we could fix what was wrong. It could be super nice to do a re-try:

try{ some_instruction(); }
catch (NearlyUnexpectedException e){
   fix_the_problem();
   retry;
}

This would quickly fall in the eternal loop, but let's say that the fix_the_problem returns true, then we retry. Given that there is no such thing in Java, how would YOU solve this problem? What would be your best design code for solving this?

This is like a philosophical question, given that I already know what I'm asking for is not directly supported by Java.


Solution

You need to enclose your try-catch inside a while loop like this: -

int count = 0;
int maxTries = 3;
while(true) {
    try {
        // Some Code
        // break out of loop, or return, on success
    } catch (SomeException e) {
        // handle exception
        if (++count == maxTries) throw e;
    }
}

I have taken count and maxTries to avoid running into an infinite loop, in case the exception keeps on occurring in your try block.



Answered By - Rohit Jain
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to handle FileNotFoundError when "try .. except IOError" does not catch it?

 August 04, 2022     exception, python, python-3.x, try-catch     No comments   

Issue

How can I catch an error on python 3? I've googled a lot but none of the answers seem to be working. The file open.txt doesn't exist so it should print e.errno.

This is what I tried now:

This is in my defined function

try:
    with open(file, 'r') as file:
        file = file.read()
        return file.encode('UTF-8')
except OSError as e:
    print(e.errno)

However I does not print anything when I get this error

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Solution

FileNotFoundError is a subclass of OSError, catch that or the exception itself:

except OSError as e:

Operating System exceptions have been reworked in Python 3.3; IOError has been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchy section in the What's New documentation.

For more details the OS Exceptions section for more information, scroll down for a class hierarchy.

That said, your code should still just work as IOError is now an alias for OSError:

>>> IOError
<class 'OSError'>

Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?



Answered By - Martijn Pieters
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I catch system-level exceptions in Linux C++?

 August 04, 2022     c++, exception, linux, try-catch     No comments   

Issue

The following catch() is not called:

void test(void)
{
    int i=1,j=0,k;
    try
    {
        k = i/j;
    }
    catch(...)
    {
        ...handle it...
    }
}

Is there a way to catch this kind of exception?


Solution

below code implement __try/__except effect like in visual studio c++ or how to simulate __try/__except for gcc or g++

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>

__thread jmp_buf * gThreadData; //thread local storage variable declare

void FPE_ExceptionHandler(int signal)
{
    printf("exception handler signalid=%d\n", signal);

    //jmp to setjmp_return and rc will equal to non zero
    longjmp(*gThreadData, 10001);
}

int main(int argc, char *argv[])
{
    //setup a callback function for access violation exception
    signal(SIGSEGV, (__sighandler_t)FPE_ExceptionHandler);

    //allocate a jmp_buf struct and assign it to thread local storage pointer
    gThreadData = (jmp_buf *)(new jmp_buf);

    //setjmp save current thread context
    int rc = setjmp(*gThreadData);

    //setjmp_return
    //first time, run to here rc will equal to 0
    if (rc == 0) {
        *(int*)0 = 1; //generate a exception
    }

    printf("return from exception\n");
    delete (jmp_buf *)gThreadData;
}


Answered By - Darwin Zou
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to implement try-catch block in racket?

 August 04, 2022     exception, lisp, racket, try-catch     No comments   

Issue

I try to write a try-catch block in racket, from the boilerplate provided here, however when I run it throws me an error.

try-catch block:

#lang racket
 (require try-catch-match)


(try [(displayln "body")
    (raise 'boom)]
   [catch (string? (printf "caught a string: ~v\n" e))
          (symbol? (printf "'e' (the value of the exception) is: ~v\n" e))])

Throws this error:

enter image description here

It says syntax error, but I really cannot see any issues. The code is from the official racket website. My goal is to write a simple try-catch block in racket, presumably using the imported library.


Solution

You're requiring try-catch-match library, but your example comes from try-catch library. These two are different and if you use the correct one, the example code will work:

#lang racket
(require try-catch)

(try [(displayln "body")
        (raise 'boom)]
       [catch (string? (printf "caught a string\n"))
              (symbol? (printf "caught a symbol\n"))])


Answered By - Martin Půda
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I figure out my issue with placing the "try" function?

 August 04, 2022     error-handling, exception, python-3.x, try-catch     No comments   

Issue

So I have been struggling to find out what is wrong with my exception code which is to only accept strings but also display text whenever there are non string inputs between the brackets which depends on where I put the "try" and except functions.

The first code I have here which 'try' is before return, any strings entered in will be accepted into the function, however the except functions will not work whenever non-strings are entered between the bottom brackets.

''' def string_processor(string):

countA = 0
if (string.isalpha()):
    for c in string:
        if c == "a":
            countA = countA + 1
try:
    return countA / len(string)  



except AttributeError:
    print("Please enter a string instead")
except IndexError:
    print("Please enter a string with quotation marks ")
else:
    print("Please only enter a string")

string_processor("000")

'''

The second code I have which I put "try:" can sort out some things such as AttributeErrors, but only strings with letters can be inputted between the brackets and any string that contains non-numbers are omitted from the function.

''' def string_processor(string):
try:
countA = 0 if (string.isalpha()): for c in string: if c == "a": countA = countA + 1

            return countA / len(string)  

except AttributeError:
    print("Please enter a string instead")
except SyntaxError:
    print("Please enter a string with quotation marks ")
else:
    print("Please only put letters in your string")

string_processor("000")

'''

I request help to fix this problem so my program can get any type of string, and will process except functions for any non-string values.


Solution

I could be wrong understanding your question. But here are my suggestions to solve your problem.

First of all, I couldn't understand your code because the else statement is not reachable there, so I slightly changed it, but nothing dramatically changed.

def string_processor(string):
    # This is a bad way to check the types and the value
    try:
        if string.isalpha():
            # If string has a type "string" and contains only letters
            return string.count('a')/len(string)
        elif string.isnumeric():
            # If string has numbers only
            print("Please enter a string instead")
    except:
        if isinstance(string, list):
            # If type of the "string" is actually a list
            print('This is not a string, this is a list')
        elif type(string) == tuple:
            # If type of the "string" is actually a tuple
            print('This is not a string, this is a tuple')
        else:
            # If none of the above worked
            print('It is definitely not a pure string')


a = string_processor(234)

As I commented, this is not a good way to implement the solution, the better way may be this:

def string_processor_another(value):
    # It is better to RAISE exceptions, not to print them
    if not isinstance(value, str):
        raise TypeError('This must be a string')
    # So if we come to this step we can be sure that we work with strings, so we can use the methods
    if value.isalpha():
        # If string has a type "string" and contains only letters
        return value.count('a')/len(value)
    elif value.isnumeric():
        # If string has numbers only
        print("Please enter a string instead")


b = string_processor_another(234)

And if you are going to add some extra logics or you want to have a cleaner code, I'd suggest you to make this in oop way

class StringProcessor:
    def __init__(self, string):
        self.__check_for_str(string)
        self.string = string

    @staticmethod
    def __check_for_str(string):
        return isinstance(string, str)

    # Here you can add short functions to make all of your logic statements

    def check_is_numeric(self):
        print(self.string.isnumeric())

    def check_is_alpha(self):
        print(self.string.isalpha())
    

sp = StringProcessor('1234')
sp.check_is_numeric() # True
sp.check_is_alpha() # False

Hope it helped.



Answered By - Valerii
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I get my main function to work while exceptions check the inputted variable?

 August 04, 2022     error-handling, exception, python, try-catch     No comments   

Issue

I managed to get my except functions working but that makes my main function not be able to work for some reason. I would really like to get my main function to work as it supposed to only accept letters and exception handle some possible errors encountered when inputting into the function.

def string_processor(string):  
    
    #The main function, 
    countA = 0
    if (string.isalpha()):
        for c in string:
            if c == "a":
                countA = countA + 1
            return (countA / len(string))
    
#finds any errors in the variable placed into the code
try:
    string_processor("aaaa")
except AttributeError:
    print("Please enter a string instead.")
except TypeError:
    print("Please input only 1 string.")
except NameError:
    print("This is not a string, please input a string")
else:
    print("String contained non-letters or unknown error occured")


For some reason, this code below is able to get the main function to work, but at the cost of only able to get Attribute errors and not the other specific errors such as TypeError and NameError.

def string_processor(string):  
    
    try:
        countA = 0
        if (string.isalpha()):
            for c in string:
                if c == "a":
                    countA = countA + 1
            return countA / len(string) 

#Exceptions
    except AttributeError:
        print("Please enter a string instead.")
    except TypeError:
        print("Please input only 1 string.")
    else:
        print("string contains non-letters or unknown error occured")
        
string_processor("1,","1")

Solution

The problem is that the else statement will be executed when the code have no exception.

Try to replace

else:
    print("string contains non-letters or unknown error occured")

to:

except Exception:
    print("String contained non-letters or unknown error occured")

or even better:

except Exception as e:
    print(e)

In this way, if you get an unexpected exception the program will print it



Answered By - Flavio Adamo
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing