This exception handler catches KeyboardInterrupt to cancel the Runner and
    also stops the Runner in case of an error.
427300
def exception_handler(exctype, value, traceback):
    
    if exctype == KeyboardInterrupt:
        pypro.console.out('')  # Adds a new line after Ctrl+C character
        pypro.console.err('Canceled')
    elif exctype == PyproException:
        pypro.console.err('[Error] ', value.message)
        exit()
    else:
        sys.__excepthook__(exctype, value, traceback)
1064310
public void stop() {

		this.logger.info( "Agent '" + getAgentId() + "' is about to be stopped." );

		// Stop the timer
		if( this.heartBeatTimer != null ) {
			this.heartBeatTimer.cancel();
			this.heartBeatTimer = null;
		}

		// Prevent NPE for successive calls to #stop()
		if( this.messagingClient == null )
			return;

		// Send a last message to the DM
		try {
			if( this.messagingClient.isConnected()) {
				this.messagingClient.sendMessageToTheDm( new MsgNotifMachineDown( this.applicationName, this.scopedInstancePath ));
				this.logger.fine( "Agent " + getAgentId() + " notified the DM it was about to stop." );
			}

		} catch( IOException e ) {
			this.logger.warning( e.getMessage());
			Utils.logException( this.logger, e );
		}

		// Close the connection
		try {
			this.messagingClient.getMessageProcessor().stopProcessor();
			this.messagingClient.getMessageProcessor().interrupt();
			this.messagingClient.closeConnection();

		} catch( IOException e ) {
			this.logger.warning( e.getMessage());
			Utils.logException( this.logger, e );
		}

		this.logger.info( "Agent '" + getAgentId() + "' was stopped." );
	}
14390
public void onCancel() {
    mSerializingExecutor.execute(() -> {
      try {
        cancelRequest(mContext);
        replyCancel();
      } catch (Exception e) {
        LogUtils.warnWithException(LOG, "Exception occurred while cancelling write request {}.",
            mContext.getRequest(), e);
        Throwables.throwIfUnchecked(e);
        abort(new Error(AlluxioStatusException.fromCheckedException(e), true));
      }
    });
  }
317054
private void skip(boolean stopAtImport, boolean stopAtMemberDecl, boolean stopAtIdentifier, boolean stopAtStatement) {
         while (true) {
             switch (token.kind) {
                case SEMI:
                    nextToken();
                    return;
                case PUBLIC:
                case FINAL:
                case ABSTRACT:
                case MONKEYS_AT:
                case EOF:
                case CLASS:
                case INTERFACE:
                case ENUM:
                    return;
                case IMPORT:
                    if (stopAtImport)
                        return;
                    break;
                case LBRACE:
                case RBRACE:
                case PRIVATE:
                case PROTECTED:
                case STATIC:
                case TRANSIENT:
                case NATIVE:
                case VOLATILE:
                case SYNCHRONIZED:
                case STRICTFP:
                case LT:
                case BYTE:
                case SHORT:
                case CHAR:
                case INT:
                case LONG:
                case FLOAT:
                case DOUBLE:
                case BOOLEAN:
                case VOID:
                    if (stopAtMemberDecl)
                        return;
                    break;
                case UNDERSCORE:
                case IDENTIFIER:
                   if (stopAtIdentifier)
                        return;
                    break;
                case CASE:
                case DEFAULT:
                case IF:
                case FOR:
                case WHILE:
                case DO:
                case TRY:
                case SWITCH:
                case RETURN:
                case THROW:
                case BREAK:
                case CONTINUE:
                case ELSE:
                case FINALLY:
                case CATCH:
                    if (stopAtStatement)
                        return;
                    break;
            }
            nextToken();
        }
    }
1009406
public void onError(Throwable cause) {
    if (cause instanceof StatusRuntimeException
        && ((StatusRuntimeException) cause).getStatus().getCode() == Status.Code.CANCELLED) {
      // Cancellation is already handled.
      return;
    }
    mSerializingExecutor.execute(() -> {
      LogUtils.warnWithException(LOG, "Exception thrown while handling write request {}",
          mContext == null ? "unknown" : mContext.getRequest(), cause);
      abort(new Error(AlluxioStatusException.fromThrowable(cause), false));
    });
  }
843123
private void handleInterruptedException(String message, InterruptedException cause) {
        Thread.currentThread().interrupt();
        throw new AbortedException(message, cause);
    }
1360170
def _stopThread(self, exception, raiseEvery=2.0):
        '''
            
        '''
        if self.isAlive() is False:
            return True

        self._stderr = open(os.devnull, 'w')

        # Create "joining" thread which will raise the provided exception
        #  on a repeat, until the thread stops.
        joinThread = JoinThread(self, exception, repeatEvery=raiseEvery)

        # Try to prevent spurrious prints
        joinThread._stderr = self._stderr
        joinThread.start()
        joinThread._stderr = self._stderr
427512
public void cancel() {
        final OnCancelListener listener;
        synchronized (this) {
            if (mIsCanceled) {
                return;
            }
            mIsCanceled = true;
            mCancelInProgress = true;
            listener = mOnCancelListener;
        }

        try {
            if (listener != null) {
                listener.onCancel();
            }
        } finally {
            synchronized (this) {
                mCancelInProgress = false;
                notifyAll();
            }
        }
    }
603661
@Override
    public void afterExecute(final Runnable runnable, final Throwable throwable) {
        super.afterExecute(runnable, throwable);
        if (throwable != null) {
            // Wrap the throwable in an ExecutionException (execute() does not do this)
            interruptionChecker.setExecutionException(new ExecutionException("Uncaught exception", throwable));
            // execute() was called and an uncaught exception or error was thrown
            interruptionChecker.interrupt();
        } else if (/* throwable == null && */ runnable instanceof Future<?>) {
            // submit() was called, so throwable is not set 
            try {
                // This call will not block, since execution has finished
                ((Future<?>) runnable).get();
            } catch (CancellationException | InterruptedException e) {
                // If this thread was cancelled or interrupted, interrupt other threads
                interruptionChecker.interrupt();
            } catch (final ExecutionException e) {
                // Record the exception that was thrown by the thread
                interruptionChecker.setExecutionException(e);
                // Interrupt other threads
                interruptionChecker.interrupt();
            }
        }
    }
351025
private void handleException(String key, Exception e) {
        if (e != null) {
            log.error(key, e.getLocalizedMessage());
            throw new Abort(e);
        } else {
            log.error(key);
            throw new Abort();
        }
    }
589364
def handle_interrupt(cancel, f, *a, **kw):
    '''
    '''
    res = []

    def run():
        res.append(f(*a, **kw))
    t = threading.Thread(target=run)
    t.start()
    # poll (or we miss the interrupt) and await completion
    try:
        while t.isAlive():
            t.join(.1)
    except KeyboardInterrupt:
        cancel()
        raise
    return res and res.pop()
278019
protected void throwException() throws InterruptedException, IOException {

        if (this.exception instanceof IOException) {
            throw (IOException) this.exception;
        }
        if (this.exception instanceof InterruptedException) {
            throw (InterruptedException) this.exception;
        }
        if (this.exception instanceof RuntimeException) {
            throw (RuntimeException) this.exception;
        }
        throw new RuntimeException(this.exception);
    }
1109628
@SuppressWarnings({"PMD.AvoidCatchingThrowable","PMD.AvoidInstanceofChecksInCatchClause"})
    public static Runnable swallowExceptions(Runnable in)
    {
        return () -> {
            try {
                in.run();
            } catch (Error tt) {
                LOGGER.error("Error (will be rethrown)", tt);
                throw tt;
            } catch (Throwable t) {
                LOGGER.error("Uncaught exception swallowed", t);
                // Ignore the IDE warning - consider Lombok's SneakyThrows, which is an abomination but heavily used by heathens, whom I pray for.
                if (t instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }
            }
        };
    }
1043916
private void handleRunAsync(RunAsync runAsync) {
		final long timeToRun = runAsync.getTimeNanos();
		final long delayNanos;

		if (timeToRun == 0 || (delayNanos = timeToRun - System.nanoTime()) <= 0) {
			// run immediately
			try {
				runAsync.getRunnable().run();
			} catch (Throwable t) {
				log.error("Caught exception while executing runnable in main thread.", t);
				ExceptionUtils.rethrowIfFatalErrorOrOOM(t);
			}
		}
		else {
			// schedule for later. send a new message after the delay, which will then be immediately executed
			FiniteDuration delay = new FiniteDuration(delayNanos, TimeUnit.NANOSECONDS);
			RunAsync message = new RunAsync(runAsync.getRunnable(), timeToRun);

			final Object envelopedSelfMessage = envelopeSelfMessage(message);

			getContext().system().scheduler().scheduleOnce(delay, getSelf(), envelopedSelfMessage,
					getContext().dispatcher(), ActorRef.noSender());
		}
	}
549264
@Override
    public final synchronized void stopService(long millis) {
        running = false;
        try {
            if (keepRunning) {
                keepRunning = false;
                interrupt();
                quit();
                if (0L == millis) {
                    join();
                } else {
                    join(millis);
                }
            }
        } catch (InterruptedException e) {
            //its possible that the thread exits between the lines keepRunning=false and interrupt above
            log.warn("Got interrupted while stopping {}", this, e);

            Thread.currentThread().interrupt();
        }
    }
386050
def _thread_excepthook():
    
    init_old = thread.Thread.__init__
    def init(self, *args, **kwargs):
        init_old(self, *args, **kwargs)
        run_old = self.run
        def run_with_except_hook(*args, **kw):
            try:
                run_old(*args, **kw)
            except (KeyboardInterrupt, SystemExit):

                raise
            except:
                sys.excepthook(*sys.exc_info())
        self.run = run_with_except_hook
    thread.Thread.__init__ = init
1267076
private void handleKey(SelectionKey key) throws IOException {
        // We could have a !isValid() key here if the connection is already closed at this point
        if (key.isValid() && key.isConnectable()) { // ie a client connection which has finished the initial connect process
            // Create a ConnectionHandler and hook everything together
            PendingConnect data = (PendingConnect) key.attachment();
            StreamConnection connection = data.connection;
            SocketChannel sc = (SocketChannel) key.channel();
            ConnectionHandler handler = new ConnectionHandler(connection, key, connectedHandlers);
            try {
                if (sc.finishConnect()) {
                    log.info("Connected to {}", sc.socket().getRemoteSocketAddress());
                    key.interestOps((key.interestOps() | SelectionKey.OP_READ) & ~SelectionKey.OP_CONNECT).attach(handler);
                    connection.connectionOpened();
                    data.future.set(data.address);
                } else {
                    log.warn("Failed to connect to {}", sc.socket().getRemoteSocketAddress());
                    handler.closeConnection(); // Failed to connect for some reason
                    data.future.setException(new ConnectException("Unknown reason"));
                    data.future = null;
                }
            } catch (Exception e) {
                // If e is a CancelledKeyException, there is a race to get to interestOps after finishConnect() which
                // may cause this. Otherwise it may be any arbitrary kind of connection failure.
                // Calling sc.socket().getRemoteSocketAddress() here throws an exception, so we can only log the error itself
                Throwable cause = Throwables.getRootCause(e);
                log.warn("Failed to connect with exception: {}: {}", cause.getClass().getName(), cause.getMessage(), e);
                handler.closeConnection();
                data.future.setException(cause);
                data.future = null;
            }
        } else // Process bytes read
            ConnectionHandler.handleKey(key);
    }