views:

1450

answers:

11

I've seen several question on here about exceptions, and some of them hint at interrupts as exceptions, but none make the connection clear.

  • What is an interrupt?

  • What is an exception? (please explain what exceptions are for each language you know, as there are some differences)

  • When is an exception an interrupt and vice-versa?

+6  A: 

An interupt is a CPU signal generated by hardware, or specific CPU instructions. These cause interupt handlers to be executed. Things such as I/O signals from I/O hardware generate interupts.

An exception can be thought of as a software-version of an interupt, that only affects its process.

I'm not sure on the exact details, but an exception could be implemented by an interupt.

TraumaPony
+2  A: 

When you are talking about interrupts and exceptions you are generally talking close to hardware level code and interrupts and exceptions are often implemented in part by hardware and part in software.

An interrupt is an event in hardware (or manually fired in assembly) that is associated with a vector of handlers that can be used to handle the interrupt's event, be it IO Completion, IO Error (Disk Memory Failure), IO Event (Mouse Move for example). The interrupts can give rise to exceptions often when some unexpected interrupt occurs.

An exception is an unexpected behavior, most often when using the hardware these come from an interrupt and are handled separately in the software using an interrupt handler. Programming languages as we see them almost always disguise this as a control structure of some kind.

bmeck
+2  A: 

In general, an interrupt is a hardware implemented trap of some sort. You register a handler for a specific interrupt (division by 0, data available on a peripheral, timer expired) and when that event happens, all processing system-wide halts, you quickly process the interrupt, and things continue on. These are usually implented in a device driver or the kernel.

An exception is a software implemented way of handling errors in code. You set up a handler for specific (or general) exceptions. When an exception occurs, the languages run-time will start unwinding the stack until it reaches a handler for that specific handler. At that point you can handle the exception and continue on, or quit your program.

Eclipse
+1  A: 

Iterrupts are basically hardware driven, like your printer indiciating it is "out of paper" or the network card indicating it has lost connection.

An exception is simply an error condition in your program, detected by a try / catch block. Like:

Try
   {
   ... various code steps that "throw exceptions" on error ...
   }
catch (exception e)
   {
   print 'Crap! Something bad happened.' + e.toString()
   }

It's a handy way to catch "any error" that happens in a block of code so you can handle them in a similar fashion.

Ron

Ron Savage
+4  A: 

Interrupts are expected to occur regularly (although sometimes they are not regular).. they interrupt the cpu because something important just happened and it needs to be taken care of immediately.

Exceptions are supposed to be exceptions to the rule; these are thrown by software because something unexpected happened and this is your chance to try to do something about it, or at the very least crash gracefully.

Giovanni Galbo
+2  A: 

I'm going to elaborate on what an interrupt is because there's one critical type of interrupt nobody has dealt with yet: the timer.

But first, let me back up. When you get an interrupt, your interrupt handler (which lives in kernelspace) runs, which typically disables interrupts, sees to any pending business (handling the packet that just arrived on the network, processing the keystroke, etc.) and then (remember we're still in the kernel at this point) figures out what process is supposed to run next (could be the same one, could be a different one, depends on the scheduler) and then run it.

Only one process runs on the processor at any given time. And when you are using a multitasking OS, the way it switches between them is called a context switch - basically the registers of the processor get dumped to memory, flow passes to the new process, and when the process is done you context switch to something else.

So, let's say I write a simple C program that counts all numbers, or the Fibonacci sequence, or something else without stopping. Or even better: does nothing but spins inside of a while(1) loop. How do the other processes on the system get a chance to run? What if there is nothing happening to cause an interrupt?

The answer is that you have a timer device that is constantly interrupting. And it is what keeps a spinning process from taking down the entire system. Although I will note that the interrupt handlers disable interrupts, so if you do something that blocks indefinitely you can take down the entire system.

Daniel Papasian
+2  A: 

Exception

An exception is when the processor executes code that is not on its normal path. This is an 'exception' to normal operation, which is essentially linear movement through code and control structures. Different languages have support for various types of exceptions, typically used to handle errors during program operation.

Interrupt

An interrupt is an exception at the hardware level (generally). The interrupt is a physical signal in the processor that tells the CPU to store its current state and jump to interrupt (or exception) handler code. Once the handler is done the original state is restored and processing can continue.

An interrupt is always an exception, even when it's intended. Interrupts might indicate:

  • errors, such as a memory access violation
  • that the OS needs to perform an operation to support a running program, such as a software interrupt, or a memory paging request
  • a hardware device requires attention, such as a received network packet, or an empty transmit buffer

These always force the processor to pause its current activity to deal with the raised exception, only resuming once the interrupt handler is complete.

Pitfalls

In terms of interrupts, common pitfalls are race conditions. For instance you might have an interrupt that periodically increments a global realtime clock. The clock might be 64 bits on a 32 bit machine.

If a program is reading the clock, and gets the first 32 bit word, then the interrupt occurs, once the interrupt handler exits the process gets the second 32 bit word, and the data will be incoherent - the two words may be out of sync. If you attempt to use a mutex or semaphore to lock the variable in the process, then the interrupt will hang waiting for the lock and halt the system (deadlock), unless both the handler and the processes that use the data are written very carefully. It's easy to get in trouble when writing for interrupts.

Re-entrant functions are also another problem. If you are executing funcA in program code, take an interrupt which also executes funcA you may end up with unintended consequences due to shared variables (static, or heap variables, classes, etc). You typically want to execute as little code as possible in the interrupt handler, and frequently have it set a flag so the process can do the real work later, without worrying about conflicts.

In some ways this is similar to developing for a multiprocessor, and is one of the reasons why kernel programming is still considered black magic by many.

Adam Davis
When you downvote, will you please explain to me what is wrong with my answer as a comment? I obviously have a lot to learn about this subject if so many disagree with my answer.
Adam Davis
+7  A: 

Your processor is going to have a number of external interrupt pins. Typically these pins are connected to hardware and are used to indicate when some external event occurs. For example, if you are using a serial port the UART will raise raise a pin that is connected to one of the interrupt pins on the processor to indicate that a byte has been received.

Other peripherals like timers, usb controllers, etc. will also generate interrupts on the basis of some external event.

When the processor receives a signal on one of it's external interrupt pins it will immediately jump to some nominated location in memory and start executing. The code executed is typically called an ISR, or interrupt service routine. Unless you're implementing drivers or doing embedded software of some sort it's unlikely that you'll ever come across ISRs.

Unfortunately the answer to the question about exceptions is a little less clear - there have been 3 different meanings listed in other answers on this page.

Ron Savage's answer refers to the software construct. This is purely an application level exception, where a piece of code is able to indicate an error that can be detected by some other piece of code. There is no hardware involvement here at all.

Then there is the exception as seen by a task. This is an operating system level construct that is used to kill a task when it does something illegal - like divide by 0, illegally accessing memory etc.

And thirdly, there is the hardware exception. In terms of behaviour it is identical to an interrupt in that the processor will immediately jump to some nominated memory location and start executing. Where an exception differs from an interrupt is that an exception is caused by some illegal activity that the processor has detected. For example the MMU on the processor will detect illegal memory accesses and cause an exception. These hardware exceptions are the initial trigger for the operating system to perform it's cleanup tasks (as described in the paragraph above).

Andrew Edgecombe
+5  A: 

Interrupts are generated by devices external to the CPU (timer tick, disk operation completion, network packet arrival, etc.) and are asynchronous with program execution. Exceptions are synchronous with program execution (e.g. division by zero, accessing an invalid address).

Unless your program is executing without an operating system (or you are developing an OS), it will never see a raw exception/interrupt. They are caught by the OS and handled by it (interrupts), or converted to some other form before being reflected back to the user program (e.g. signals on UNIX, structured exception handling (SEH) on Windows) where it has a chance of handling it.

zvrba
A: 

Keeping things simple...

When you are done handling an interrupt, you (normally) return to what you were doing before you were interrupted.

Handling an exception involves throwing away successive layers of what you are currently working on until you bubble up to a point where the exception can be handled (caught).

While handling an interrupt, you may decide to throw an exception, but that doesn't mean you have to consider the interrupt itself as an exception. Exceptions do not "interrupt" (since that would imply the possibility of returning to what you were doing just before you were interrupted); rather they "abort" (some subset of) your current activity.

And, as noted several times already, interrupts are usually triggered by outside entities such as hardware or users (such as a mouse click or keystroke like CTRL-C) while exceptions are generated (thrown) synchronously by software detecting a "problem" or "exceptional condition".

tye
+1  A: 

Interrupts indicate that something external to the processor core requires it's attention. It interrupts the normal flow of the program, executes an Interrupt Service Routine (ISR) and generally returns to where it was before the interrupt occurred.

There are lots of variation on this basic theme: interrupts might be generated by software, another task might get the CPU after the ISR, etc.. The key point is that interrupts can occur at any time for a reason the code/CPU has no control over.

An exception is a bit trickier to define because it has potentially three levels of meaning:

Hardware Exceptions

Certain processors (PowerPC for example) define exceptions to indicate that some sort of unusual condition has occurred: System Reset, Invalid Address, some virtual address translation cache miss, etc...

These exceptions are also used to implement breakpoints and system calls. In this case, they act almost like interrupts.

OS Exceptions

Some of the hardware exceptions will the handled by the OS. For example, your program accesses invalid memory. This will cause a hardware exception. The OS has a handler for that exception, and odds are that the OS will send a signal to your application (SIGSEGV for example) denoting there is a problem.

If your program has a signal handler installed, the signal handler will run and hopefully deal with the situation. If you don't have a signal handler, the program can be terminated or suspended.

I would consider window's Structured Exception Handlers (SEH) to be this type of exceptions.

Software Exceptions

Some languages like Java, C++ and C# have the concept of software exceptions, where the language provides for the handling of unforeseen or unusual conditions related to the operation of the program. In this case, an exception is raised at some point in the code and some code higher up on the program execution stack would "catch" the exception and execute. This is what try/catch blocks do.

Benoit