C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

static jmp_buf s_jumpBuffer;

void Example() { 
  if (setjmp(s_jumpBuffer)) {
    // The longjmp was executed and returned control here
    printf("Exception happened here\n");
  } else {
    // Normal code execution starts here
    Test();
  }
}

void Test() {
  // Rough equivalent of `throw`
  longjmp(s_jumpBuffer, 42);
}

This website has a nice tutorial on how to simulate exceptions with setjmp and longjmp

  • http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html
Answer from JaredPar on Stack Overflow
Top answer
1 of 9
182

It depends on whether you can deal with the exceptions that can be raised at this point or not.

If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.

If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

2 of 9
40

The finally block is used for code that must always run, whether an error condition (exception) occurred or not.

The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.

The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.

Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.

Discussions

c# - Use a 'try-finally' block without a 'catch' block - Stack Overflow
Are there situations where it is appropriate to use a try-finally block without a catch block? More on stackoverflow.com
🌐 stackoverflow.com
Exception handling: 'catch' without explicit 'try' - Programming Language Design and Implementation Stack Exchange
For instance, it allowed a definition ... value = try Foo() else catch; $\endgroup$ ... $\begingroup$ What is a scope in your language? A function? A statement? Something else? What happens when catch is in the middle of a block - does its scope span the entire block, including after it? Does your language have the means to explicitly create a new ... More on langdev.stackexchange.com
🌐 langdev.stackexchange.com
June 27, 2024
try {} catch {} blocks in C
setjmp()/longjmp() are handy for this. Lets you raise errors from nested functions. More on reddit.com
🌐 r/C_Programming
39
1
July 20, 2022
c# - Why can't I write just a try with no catch or finally? - Stack Overflow
With most languages, there is no ... than to try+catch within the loop, and build the log in the catch handler. (You could build a mroe flexible mechanism, though: Have a per-call-thread handler that can either throw, or stow away the message. However, interaction with debugging tools suffers without direct language ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › cs › cs_exceptions.php
C# Exceptions (Try..Catch)
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
🌐
GeeksforGeeks
geeksforgeeks.org › software engineering › try-catch-block-in-programming
Try Catch Block in Programming - GeeksforGeeks
July 23, 2025 - The try block contains code that ... prevents program termination when exceptions occur. Remember, we can use a try block without a catch block, but not vice versa....
🌐
Dotnet Tutorial
dotnetustad.com › c-sharp › try-block-without-catch-block
Can we have only try block without catch block?
Indeed, it's possible to use a try block without pairing it with a catch block. Often this approach is taken when executing code that may trigger an exception, yet there's no requirement to immediately address this exception within that segment ...
🌐
Sololearn
sololearn.com › en › Discuss › 1379946 › can-be-a-try-block-without-catch
Can be a try block without catch? | Sololearn: Learn to code for FREE!
July 1, 2018 - You can't write only try block it will throw you a compile time error. if you write try then you need to write either catch or finally block.
Find elsewhere
Top answer
1 of 10
193

You would use it to ensure some actions occur after the try content or on an exception, but when you don't wish to consume that exception.

Just to be clear, this doesn't hide exceptions. The finally block is run before the exception is propagated up the call stack.

You would also inadvertently use it when you use the using keyword, because this compiles into a try-finally (not an exact conversion, but for argument's sake it is close enough).

try
{
    TrySomeCodeThatMightException();
}
finally
{
    CleanupEvenOnFailure();
}

Code running in finally is not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the finally isn't your biggest problem :-) so basically don't sweat it.

Update from Tobias: finally will not run if the process is killed.

Update from Paddy: Conditions when finally does not execute in a .net try..finally block

The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:

using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-)
{
    // Do stuff.
}

Compiles into something like:

SqlConnection conn;

try
{
    conn = new SqlConnection("");
    // Do stuff.
}
finally
{
    if (conn != null)
        conn.Dispose();
}
2 of 10
12

Good Explaination using code:

void MyMethod1()
{
    try
    {
        MyMethod2();
        MyMethod3();
    }
    catch(Exception e)
    {
        //do something with the exception
    }
}


void MyMethod2()
{
    try
    {
        //perform actions that need cleaning up
    }
    finally
    {
        //clean up
    }
}


void MyMethod3()
{
    //do something
}

If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

http://forums.asp.net/t/1092267.aspx?Try+without+Catch+but+with+finally+doesn+t+throw+error+Why+no+syntax+error+

🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › language-reference › statements › exception-handling-statements
Exception-handling statements - throw and try, catch, finally - C# reference | Microsoft Learn
DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException("Conversion to a DateTime is not supported."); You can use the try statement in any of the following forms: try-catch - to handle exceptions that might occur during execution of the code inside a try block, try-finally - to specify the code that runs when control leaves the try block, and try-catch-finally - as a combination of the preceding two forms.
🌐
Quora
quora.com › Can-try-be-used-without-catch
Can try be used without catch? - Quora
Exceptions (computer prog... ... Yes. In many programming languages a try block can be used without an accompanying catch block, provided it is paired with a finally (or equivalent) construct that guarantees cleanup.
🌐
GitHub
gist.github.com › rampion › 91594
TRY/CATCH/FINALLY macros for C · GitHub
TRY/CATCH/FINALLY macros for C. GitHub Gist: instantly share code, notes, and snippets.
Top answer
1 of 5
7

If try is technically just a scope marker, it is functionally redundant when scopes are already clear. It is no problem to define a language in which try can be "folded" directly into a preceding scope marker.

For example, it is trivial to treat

while ...
  ...
catch e
  ...

as syntactic sugar for

while ...
  try
    ...
  catch e
    ...

which is similar to Ruby's semantics.

Relatedly, if your language is expression based you can have an <expr> catch <name> <expr(name)> construct/operator/... that trivially expands to a longer form. For example, this even was proposed for Python and only rejected for non-technical reasons.


What you should ask yourself is if exception handling for an entire, given scope is actually a good thing. Consider that your tiny example is intended to catch an error from factorial, but actually it would handle two to three things.

To clarify, let me write that part the way I would do for my dayjob:

try:
   result = factorial(i)
except e:
   print('Factorial of', i, 'resulted in', e.message)
   break
else:
   print('Factorial of', i, 'is', result)
   i += 1

Notice how the factorial handler really only deals with the factorial execution! It does not handle whether formatting strings works, whether printing works, or even whether incrementing works. These are all actions where an error is not expected by your handler, so if one does occur it should absolutely be loud and definitely not accidentally silenced.
Precisely handling errors is something you absolutely do want to offer. And probably (since correct error handling is your goal) you don't just want to offer it, but also encourage it - or even discourage imprecise error handling!

By inviting people to be sloppy and re-use logical scopes as error scopes, you make error handling worse. So at the very least, you should offer something to add explicit scopes. This can be a generic scope mechanism, and in your example syntax it would map to a separate keyword:

while ...
  .
  .
  scope
    .
  catch e
    ...

But at this point you are almost all the way to having try, especially if the scope has little or no other use. So basically you have to ask yourself whether you are willing to pay the price of having a try keyword or not - because most if not all of the other cost you should be prepared to pay anyway.

2 of 5
5

The lack of an explicit try makes it harder to catch exceptions from only some places.

Put together with your other proposal to make exceptions homogeneous, it will be harder in multiple ways for programmers to catch and handle some exceptional cases while allowing others to propagate. It will also be more likely that programmers will mistakenly catch (and accidentally suppress) exceptions they did not intend to.


Consider code like this:

file = acquire_foo()

try:
    foo.bar()
    foo.baz()
catch:
    print('failed to bar and baz the foo')

This shape of code is very common, where we want to acquire a resource and do something with it, and handle the error if the latter fails. Note that the try: specifically occurs after acquire_foo(), meaning if we fail to acquire the resource, the exception will not be caught. This is the programmer's intention, but expressing that intention requires an explicit try. There is no easy way to write this code otherwise.

You could get around this by making catch only apply to the preceding statement, and allowing grouping using optional braces:

foo = acquire_foo()

{ // these together are one statement
    foo.bar()
    foo.baz()
}
catch:
    // this only catches exceptions from the previous block statement
    ...

However, besides having the same indentation you were trying to avoid by omitting try, this is an accident waiting to happen. People will forget to do this. It's particularly a problem when acquire_foo() and foo.bar() can signal the same type of exception (e.g. a database error), because if you catch from both by accident, you'll mishandle acquire_foo()'s error as if it was thrown by foo.bar().

🌐
Reddit
reddit.com › r/c_programming › try {} catch {} blocks in c
r/C_Programming on Reddit: try {} catch {} blocks in C
July 20, 2022 -

First of all: THIS IS NOT TRYING TO EMULATE C++ EXCEPTIONS.

Something I wish we have in C is a external block that we can jump out of it. Along the years suggestions like break break have appeared to be possible jump to an external point without gotos. My main usage of this kind of jump is to break normal sequence of statements when some error happens. So..this is the reason try catch names where chosen. But this is a LOCAL jump and I think this is an advantage not an limitation.

Emulation using macros:

#define try  if (1)
#define catch else catch_label:
#define throw goto catch_label

Usage:

FILE * f = NULL;
try
{
   f = fopen("file.txt", "r");
   if (f == NULL) throw;
   ...
   if (some_error) throw;

   /*success here*/
}
catch
{
   /*some error*/
}

if (f) 
  close(f);

For a language feature catch could be optional. But emulating it using macros it is required.

What do you think? Any better name for this?

For the jump without error the C language could have a simular block without catch maybe with some other name.

Macro emulation also have a limitation of more than one try catch blocks and nested try catch blocks. For nested try catch the design for a language feature would probably jump to the inner catch and then you can use throw again inside catch to jump to the more external catch.

🌐
Java2Blog
java2blog.com › home › core java › exception handling › can we have try without catch block in java
Can We Have Try without Catch Block in Java - Java2Blog
February 19, 2024 - In Java, it’s possible to use a try block without a catch block, but it must be followed either by a finally block or be part of a try-with-resources statement. ... You can use a try block with a finally block. As you may know, the finally block always executes, even if there is an exception ...
Top answer
1 of 10
45

If you don't want to catch it, why are you using try in the first place?

A try statement means that you believe something can go wrong, and the catch says that you can adequately handle that which goes wrong.

So in your estimation:

try
{
    //Something that can go wrong
}
catch
{
    //An empty catch means I can handle whatever goes wrong. If a meteorite hits the
    //datacenter, I can handle it.
}

That catch swallows any exceptions that happen. Are you that confident in your code that you can handle anything that goes wrong gracefully?

The best thing to do (for both yours and your maintenance programmer's sanity) is to explicitly state that which you can handle gracefully:

try
{
    //Something that could throw MeteoriteHitDatacenterException
}
catch (MeteoriteHitDatacenterException ex)
{
    //Please log when you're just catching something. Especially if the catch statement has side effects. Trust me.
    ErrorLog.Log(ex, "Just logging so that I have something to check later on if this happens.")

}
2 of 10
11

No, you should not catch every important exception. It is okay to catch and ignore exceptions you don't care about, like an I/O error if there's nothing you can do to correct it and you don't want to bother reporting it to the user.

But you need to let exceptions like StackOverflowException and OutOfMemoryException propagate. Or, more commonly, NullReferenceException. These exceptions are typically errors that you did not anticipate, cannot recover from, should not recover from, and should not be suppressed.

If you want to ignore an exception then it is good to explicitly write an empty catch block in the code for that particular exception. This makes it clear exactly what exceptions you're ignoring. Ignoring exceptions very correctly is an opt-in procedure, not an opt-out one. Having an "ignore all exceptions" feature which can then be overridden to not ignore specific types would be a very bad language feature.

How do you know what types of exceptions are important and should not be caught? What if there are exceptions you don't know about? How do you know you won't end up suppressing important errors you're not familiar with?

try
{
}
// I don't care about exceptions.
catch
{
}
// Okay, well, except for system errors like out of memory or stack overflow.
// I need to let those propagate.
catch (SystemException exception)
{
    // Unless this is an I/O exception, which I don't care about.
    if (exception is IOException)
    {
        // Ignore.
    }
    else
    {
        throw;
    }
}
// Or lock recursion exceptions, whatever those are... Probably shouldn't hide those.
catch (LockRecursionException exception)
{
    throw;
}
// Or, uh, what else? What am I missing?
catch (???)
{
}
🌐
Sololearn
sololearn.com › en › Discuss › 2271869 › does-try-block-work-without-catch-in-c
Does "try block" work without "catch" in C#? | Sololearn: Learn to code for FREE!
In a C# challenge, the question is "Can we have only try block without catch block in C#?" I answer "No" and I got "Wrong". In C#, "try block" really works without "ca
🌐
GitHub
github.com › dotnet › csharplang › issues › 220
Discussion: `try` expression without `catch` for inline use · Issue #220 · dotnet/csharplang
March 3, 2017 - Sometimes it is not necessary to catch an exception, because you can either check side conditions or proceed though the expression is failed. In these cases it would be nice to skip the exception checking.
Author   lachbaer
🌐
C# Corner
c-sharpcorner.com › UploadFile › skumaar_mca › exception-handling-in-C-Sharp
Exception handling in C#
September 29, 2012 - Try...Catch block can be defined without finally or Catch. But Try statement must be defined with either Catch or finally block. Without both Try block cannot be executed independently.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › try...catch
try...catch - JavaScript - MDN Web Docs - Mozilla
March 9, 2026 - Statement that is executed if an exception is thrown in the try block. ... An optional identifier or pattern to hold the caught exception for the associated catch block. If the catch block does not use the exception's value, you can omit the exceptionVar and its surrounding parentheses.
🌐
Quora
quora.com › Is-it-possible-to-implement-a-catch-block-without-try-blocks
Is it possible to implement a catch block without try blocks? - Quora
Answer (1 of 3): No, it is not possible because the catch block would be useless as there is no piece of code to throw an exception. The try and catch block always come in pairs like this: [code]try{ //code that could fail //example: value = ...