try in python except and tryCatch Exception Resolution in R

  • 2021-12-12 08:54:25
  • OfStack

Directory 1. Cause 2. try/except1 in Python) Situation 12) Situation 23) Situation 33. tryCatch1 in R) Situation 12) Situation 23) Situation 3 Supplement

1. Causes

When we need to write a very, very long loop, usually in a loop, if error occurs, then the loop behind the whole code cannot proceed.

At this time, imagine that if you hang a loop (parallel) that takes a long time to run on the server, or need to hang something on your computer for one night to run, you may have just finished running, and after going to bed happily, the program suddenly has problems. At this time, the next day, I lit up the screen with full expectation and found that it was a big red one ERROR At that time, it is estimated that the hair may be thinner again.

So at this time, I wonder if we can bypass these problems and carry out the next cycle when running, if there is an error in the program.

In fact, this kind of problem lies in Python And R In, there are corresponding solutions.

2. try/except in Python

First, post the official description document:

English document: https://docs.python.org/3/tutorial/errors.html

Chinese document: https://docspy3zh. readthedocs.io/en/lates t/tutorial/errors. html

Here we mimic the example in the middle of the document to construct our own example, as shown in the following code.


def divide(x, y):
    try:
        result = x / y
        
    except ZeroDivisionError:
        print("division by zero!")
    
    except:
        print('unknown error ! ')
    
    else:
        print("result is", result)
        
    finally:
        print("executing finally clause")

Explain the program logic here: first run try If:

If you don't report an error, you will jump to else , finally arrive final

An error with a denominator of 0 will skip to except ZeroDivisionError And then ignore it directly else To the last finally

Other types of errors are ignored exc Python0 , and then to except , and then ignore it else To the last finally

That is to say, in any case, finally They all work.

Let's validate three inputs:

1) Case 1

Enter:


divide(2, 1)

Output:


result is 2.0
executing finally clause

2) Case 2

Enter:


divide(2, 0)

Output:


division by zero!
executing finally clause

3) Case 3


divide("2", "1")

Output:


error ! 
executing finally clause

3. tryCatch in R

Similarly, in R In tryCatch Function also solves similar problems.

Refer to the official documentation: trycatch: Evaluates an expression with the possibility to catch exceptions (DEPRECATED)

Then run a similar program above to see the usage


divide <- function(x, y) {
  result <- tryCatch({
    x / y
  }, warning = function(war) {
    cat("warning!", war, "\n")
  }, error = function(err) {
    cat("error!", err, "\n")
  }, finally = {
    print("executing finally clause")
  })
  
  return(result)
}

What needs special attention here is that, tryCatch After that, you should add braces and braces. In addition, I added err This object is equivalent to outputting an error message.

The following is the running result:

1) Case 1

Enter:


divide(1, 2)

Output:


[1] "executing finally clause"
[1] 0.5

I was the first finally , again R0 So it will be the output above.

2) Case 2

Enter:


divide(2, 1)
0

Output:


divide(2, 1)
1

Note that R outputs R1 This is different from Python.

3) Case 3

Enter:


divide(2, 1)
2

Output:


error! 
 Error in cat("error!", err, "\n") : 
  argument 2 (type 'list') cannot be handled by 'cat'
[1] "executing finally clause"

Supplement

Finally, if we want to R Ignore some codes that may report errors (do not need to output any error information), and use it directly try() That's enough.

The above is python try except and R language tryCatch exception resolution details, more about python and R language exception resolution information please pay attention to other related articles on this site!


Related articles: