Questions tagged [try-catch]

try-catch is a syntactic construct for catching exceptions raised by a code section

try-catch
Filter by
Sorted by
Tagged with
50 votes
3 answers
30k views

How can I write an empty indented block in Python?

I have some code like: try: do_the_first_part() except SomeError: do_the_next_part() I get an error that says "expected an indented block" - but I don't want to write anything inside my ...
Jader Dias's user avatar
  • 89.4k
531 votes
6 answers
557k views

How to use the tryCatch() function?

I want to write code using tryCatch to deal with errors downloading data from the web. url <- c( "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html", "...
Dd Pp's user avatar
  • 5,847
418 votes
19 answers
342k views

Why is "except: pass" a bad programming practice?

I often see comments on other Stack Overflow questions about how the use of except: pass is discouraged. Why is this bad? Sometimes I just don't care what the errors are and I want to just continue ...
Vader's user avatar
  • 6,556
142 votes
6 answers
138k views

Correct Try...Catch Syntax Using Async/Await

I like the flatness of the new Async/Await feature available in Typescript, etc. However, I'm not sure I like the fact that I have to declare the variable I'm awaiting on the outside of a try...catch ...
freedomflyer's user avatar
  • 2,531
423 votes
14 answers
272k views

Can I try/catch a warning?

I need to catch some warnings being thrown from some php native functions and then handle them. Specifically: array dns_get_record ( string $hostname [, int $type= DNS_ANY [, array &$authns [...
user121196's user avatar
  • 30.6k
1466 votes
19 answers
1.5m views

Catch and print full Python exception traceback without halting/exiting the program

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 ...
chriscauley's user avatar
  • 20.1k
126 votes
14 answers
105k views

Catching java.lang.OutOfMemoryError?

Documentation for java.lang.Error says: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch But as java.lang.Error is a ...
Denis Bazhenov's user avatar
570 votes
11 answers
349k views

Is it a good practice to use try-except-else in Python?

From time to time in Python, I see the block: try: try_this(whatever) except SomeException as exception: #Handle exception else: return something What is the reason for the try-except-else ...
Juan Antonio Gomez Moriano's user avatar
137 votes
10 answers
132k views

C# catch a stack overflow exception

I have a recursive call to a method that throws a stack overflow exception. The first call is surrounded by a try catch block but the exception is not caught. Does the stack overflow exception ...
Toto's user avatar
  • 7,599
215 votes
20 answers
160k views

Why are empty catch blocks a bad idea? [closed]

I've just seen a question on try-catch, which people (including Jon Skeet) say empty catch blocks are a really bad idea? Why this? Is there no situation where an empty catch is not a wrong design ...
Samuel Carrijo's user avatar
58 votes
4 answers
32k views

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

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 ...
Aaron left Stack Overflow's user avatar
719 votes
18 answers
314k views

Why catch and rethrow an exception in C#?

I'm looking at the article C# - Data Transfer Object on serializable DTOs. The article includes this piece of code: public static string SerializeDTO(DTO dto) { try { XmlSerializer ...
corlettk's user avatar
  • 13.4k
866 votes
11 answers
686k views

Can I catch multiple Java exceptions in the same catch clause?

In Java, I want to do something like this: try { ... } catch (/* code to catch IllegalArgumentException, SecurityException, IllegalAccessException, and NoSuchFieldException at ...
froadie's user avatar
  • 81.5k
212 votes
15 answers
357k views

How using try catch for exception handling is best practice

while maintaining my colleague's code from even someone who claims to be a senior developer, I often see the following code: try { //do something } catch { //Do nothing } or sometimes they write ...
Toan Nguyen's user avatar
  • 11.4k
153 votes
8 answers
51k views

Better to 'try' something and catch the exception or test if it's possible first to avoid an exception?

Should I test if something is valid or just try to do it and catch the exception? Is there any solid documentation saying that one way is preferred? Is one way more pythonic? For example, should I: ...
chown's user avatar
  • 52.3k
341 votes
13 answers
119k views

Do try/catch blocks hurt performance when exceptions are not thrown?

During a code review with a Microsoft employee we came across a large section of code inside a try{} block. She and an IT representative suggested this can have effects on performance of the code. In ...
Kobi's user avatar
  • 137k
480 votes
16 answers
105k views

Why should I not wrap every block in "try"-"catch"?

I have always been of the belief that if a method can throw an exception then it is reckless not to protect this call with a meaningful try block. I just posted 'You should ALWAYS wrap calls that can ...
Konrad's user avatar
  • 40.3k
50 votes
5 answers
41k views

Try With Resources vs Try-Catch [duplicate]

I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs ...
computerquest's user avatar
221 votes
7 answers
62k views

Is it expensive to use try-catch blocks even if an exception is never thrown?

We know that it is expensive to catch exceptions. But, is it also expensive to use a try-catch block in Java even if an exception is never thrown? I found the Stack Overflow question/answer Why are ...
jsedano's user avatar
  • 4,146
9 votes
4 answers
15k views

VBA: How long does On Error Resume Next work?

I'm reading up on how to use On Error Resume Next and I'm trying to figure out how long that line will apply to the program. On the Microsoft site, I found this sentence: "An On Error Resume Next ...
Tawm's user avatar
  • 545
85 votes
11 answers
100k views

Does the C# "finally" block ALWAYS execute? [duplicate]

Possible Duplicate: Will code in a Finally statement fire if I return a value in a Try block? Consider the following code C# code. Does the "finally" block execute? public void DoesThisExecute() ...
Ryan Rodemoyer's user avatar
54 votes
5 answers
25k views

catch exception by pointer in C++

I found that there are three ways to catch an exception, what are the differences? 1) catch by value; 2) catch by reference; 3) catch by pointer; I only know that catch by value will invoke two ...
skydoor's user avatar
  • 25.5k
0 votes
3 answers
4k views

Program freezes during Thread.sleep() and with Timer

Original question: This method is supposed to change the image being displayed on a JFrame gradually into another image. However, without some way to slow it down, it just seems to change from one ...
Ruben Martinez Jr.'s user avatar
262 votes
29 answers
318k views

How do you implement a re-try-catch?

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 ...
Andres Farias's user avatar
122 votes
7 answers
156k views

Capture keyboardinterrupt in Python without try-except

Is there some way in Python to capture KeyboardInterrupt event without putting all the code inside a try-except statement? I want to cleanly exit without trace if user presses Ctrl+C.
Alex's user avatar
  • 2,019
68 votes
5 answers
31k views

Why is `.catch(err => console.error(err))` discouraged?

I'm using promises and have code that looks like the following: function getStuff() { return fetchStuff().then(stuff => process(stuff) ).catch(err => { console.error(err); }); } ...
Benjamin Gruenbaum's user avatar
63 votes
5 answers
66k views

Why does a Try/Catch block create new variable scope?

For example: try { SomeObject someObject = new SomeObject(); someObject.dangerousMethod(); } catch(Exception e) { } someObject.anotherMethod(); //can't access someObject! But you can declare ...
telkins's user avatar
  • 10.5k
113 votes
5 answers
175k views

How to catch segmentation fault in Linux?

I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I ...
Alex F's user avatar
  • 42.9k
60 votes
3 answers
78k views

C++, __try and try/catch/finally

I'm wondering a bit about C++ try/catch/finally blocks. I've seen these commands with two underscores like __try. But MVSC 2010 projects also run without the underscores. So when do you need these ...
martin's user avatar
  • 1,129
260 votes
12 answers
93k views

Will code in a Finally statement fire if I return a value in a Try block?

I'm reviewing some code for a friend and say that he was using a return statement inside of a try-finally block. Does the code in the Finally section still fire even though the rest of the try block ...
JamesEggers's user avatar
  • 12.9k
95 votes
2 answers
148k views

Try-catch-finally-return clarification [duplicate]

By reading all the questions already asked in this forum related to the topic above (see title), I thoroughly understand that finally gets always called. (except from System.exit and infinite loops). ...
Rollerball's user avatar
  • 12.9k
22 votes
3 answers
31k views

Problem with "scopes" of variables in try catch blocks in Java

Could anyone explain me why in the last lines, br is not recognized as variable? I've even tried putting br in the try clause, setting it as final, etc. Does this have anything to do with Java not ...
devoured elysium's user avatar
83 votes
8 answers
92k views

How to catch the fatal error: Maximum execution time of 30 seconds exceeded in PHP

I've been playing around with a system I'm developing and managed to get it to cause this: Fatal error: Maximum execution time of 30 seconds exceeded It happened when I was doing something ...
ingh.am's user avatar
  • 26.3k
235 votes
9 answers
120k views

try/catch + using, right syntax

Which one: using (var myObject = new MyClass()) { try { // something here... } catch(Exception ex) { // Handle exception } } OR try { using (var myObject = new ...
Xaqron's user avatar
  • 30.4k
49 votes
12 answers
103k views

How to catch the null pointer exception? [duplicate]

try { int* p = 0; *p = 1; } catch (...) { cout << "null pointer." << endl; } I tried to catch the exception like this but it doesn't work,any help?
mindhacks's user avatar
  • 519
33 votes
5 answers
12k views

Main method code entirely inside try/catch: Is it bad practice?

Usually I put all of my Main method code inside of a try/catch block like so: public static void Main(string[] args) { try { // code } catch (Exception e) { // code } } ...
TheBoss's user avatar
  • 759
131 votes
7 answers
37k views

How do exceptions work (behind the scenes) in c++

I keep seeing people say that exceptions are slow, but I never see any proof. So, instead of asking if they are, I will ask how do exceptions work behind the scenes, so I can make decisions of when to ...
user avatar
103 votes
12 answers
29k views

What is the real overhead of try/catch in C#?

So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact?
JC Grubbs's user avatar
  • 39.7k
49 votes
4 answers
30k views

How to tell lapply to ignore an error and process the next thing in the list?

I have an example function below that reads in a date as a string and returns it as a date object. If it reads a string that it cannot convert to a date, it returns an error. testFunction <- ...
John  's user avatar
  • 5,169
33 votes
1 answer
23k views

try..catch not catching async/await errors

Perhaps I misunderstood how catching errors with async/await is supposed to work from things articles like this https://jakearchibald.com/2014/es7-async-functions/ and this http://pouchdb.com/2015/03/...
azium's user avatar
  • 20.4k
191 votes
10 answers
150k views

How do I prevent node.js from crashing? try-catch doesn't work

From my experience, a php server would throw an exception to the log or to the server end, but node.js just simply crashes. Surrounding my code with a try-catch doesn't work either since everything is ...
TiansHUo's user avatar
  • 8,609
100 votes
5 answers
139k views

Use tryCatch skip to next value of loop upon error?

I've read a few other SO questions about tryCatch and cuzzins, as well as the documentation: Exception handling in R catching an error and then branching logic How can I check whether a function call ...
isomorphismes's user avatar
43 votes
4 answers
6k views

Difference between try-catch syntax for function

I came across this syntax recently for try-catch for function. struct A { int a; A (int i) : a(i) // normal syntax { try {} catch(...) {} } A () // something different try : ...
iammilind's user avatar
  • 69.1k
29 votes
2 answers
44k views

try-catch exceptions in Swift [duplicate]

Is it possible to catch exceptions in Swift? Given the following code: NSException.raise(NSRangeException, format: "Now you've gone too far!", arguments: CVaListPointer(fromUnsafePointer: ...
Brian Gesiak's user avatar
  • 6,838
17 votes
1 answer
2k views

try with resources introduce unreachable bytecode

Is it possible that javac generates unreachable bytecode for the following procedure? public void ex06(String name) throws Exception { File config = new File(name); try (FileOutputStream fos =...
Martin Schäf's user avatar
6 votes
1 answer
995 views

Why do catch clauses have their own lexical environment?

Consider the following excerpt from ECMA-262 v5.1 (which I recently saw in this question): A Lexical Environment is a specification type used to define the association of Identifiers to specific ...
bfavaretto's user avatar
  • 71.9k
90 votes
4 answers
50k views

In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?

Is it "slow" to use several try-catch blocks when no exceptions are thrown in any of them? My question is the same as this one, but for JavaScript. Suppose I have 20 functions which have try-catch ...
cprcrack's user avatar
  • 18.2k
67 votes
9 answers
33k views

Performance of try-catch in php

What kind of performance implications are there to consider when using try-catch statements in php 5? I've read some old and seemingly conflicting information on this subject on the web before. A ...
Travis's user avatar
  • 858
65 votes
3 answers
28k views

Are destructors called after a throw in C++?

I ran a sample program and indeed destructors for stack-allocated objects are called, but is this guaranteed by the standard?
Luchian Grigore's user avatar
79 votes
7 answers
98k views

How to catch this error: "Notice: Undefined offset: 0"

I want to catch this error: $a[1] = 'jfksjfks'; try { $b = $a[0]; } catch (\Exception $e) { echo "jsdlkjflsjfkjl"; } Edit: in fact, I got this error on the following line: $parse = $xml-&...
meotimdihia's user avatar
  • 4,241

1
2 3 4 5
19