• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

How do exceptions really work?

When an exception occurs (wether because of an error or if it's explicitely thrown), what does really happen? If there's a catch block, it goes to that, if there's no catch block, it exits a function and goes to the next one on call stack? If the rest of the function where an exception happens doesn't depend on the code that caused the exception, can I just use goto in the catch block and ignore it?
3 Solutions
If an exception occurs and no try catch block is used, the program will terminate.  It will not execute the next function in the call stack.  You don't want to ignore exceptions, but if you want, you can just have a catch block that does nothing in the catch.

For example:

try {
  // simulate an exception getting thrown by something
  throw new ApplicationException();
catch {

// this function will still be executed


A try...catch block is used for Error handling.
  That does not mean that you cant write a program witout try..catch block, you could. You check everything and see if all status is okay and then you do your work. Infact this is how error handling is done before try...catch was introduced. The concept of try..catch is you assume that everything is okay, and you just work around, you dont worry about the error. You just include the code that has the chances to fail inside the try block. and you write the code inside the catch block which has to executed when the try block fails. That is it. The program is executed, and any error is occured, the try block is stopped at that point and the catch block is executed, and the rest of the code is exectued normally, unless you quit the function inside the catch block. If no error is occured, then the catch block is omited.
So simple as that.
There is another part in try...catch, it is called finally. not everyone uses this, it is because it as same as the code that is placed after the try...catch block.

   code block 1

  code block 2
 code block 3
code block 4

   The code blocks 3 and 4 is executed always. code block 2 is only executed if any error is occured in code block 1. Code block 1 is executed and if any error occurs, it bypasses the rest code in code block 1

  So you can the finally block when u have some clean up process which is used in the try...catch block.
You can also have many cacth block each catching different execptions
for further reference goto

gromulAuthor Commented:

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now