You want the error= argument to tryCatch to be the function that computes the intergral by the backup method. The finally= argument is treated as an expression (not a function) that is evaluated (not called) after all the other work in tryCatch has been done. The value of the evaluated finally expression appears to be ignored.
E.g., > z <- tryCatch({message("Calling seq_len"); seq_len(-1)}, + error=function(cond){message("Encountered an error: ", cond) ; integer(0)}, + finally={message("Finally"); NA}) Calling seq_len Encountered an error: Error in seq_len(-1): argument must be coercible to non-negative integer Finally > z integer(0) or, the same example with a main expression that does not throw an error, > z <- tryCatch({message("Calling seq_len"); seq_len(7)}, + error=function(cond){message("Encountered an error: ", cond) ; integer(0)}, + finally={message("Finally"); NA}) Calling seq_len Finally > z [1] 1 2 3 4 5 6 7 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf Of statfan > Sent: Sunday, October 30, 2011 6:24 PM > To: r-help@r-project.org > Subject: [R] tryCatch with integration > > I am trying to compute the approximate numerical integration of the following > expression using the integrate function: > > > > (integrate(function(x) {log(1+x^2)*(1+x^2)^(-20.04543)},low,Inf)$val) > Error in integrate(function(x) { : the integral is probably divergent > > > which gives me an error. If this error happens I want to return the > following instead > > > (area(function(x) {-2*log(cos(x))*(cos(x)^(2*e-2))}, atan(low), pi/2)) > [1] 0.01045636 > > In order to accomplish this I tried the following: > > > this= tryCatch((integrate(function(x) > > {log(1+x^2)*(1+x^2)^(-e)},low,Inf)$val),error=function(e) e, finally = > > (area(function(x) {-2*log(cos(x))*(cos(x)^(2*e-2))}, atan(low), pi/2))) > > this > <simpleError in integrate(function(x) { log(1 + x^2) * (1 + x^2)^(-e)}, > low, Inf): the integral is probably divergent> > > Perhaps I am using tryCatch incorrectly? Any help would be greatly > appreciated. > > -- > View this message in context: > http://r.789695.n4.nabble.com/tryCatch-with-integration- > tp3954528p3954528.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.