FAQ Database Discussion Community


How to in Scala handle NoSuchElementException without throwing exception

scala,exception-handling
I'm using Play framework by Scala. I have Postgresql database. It fetches data by following code:- def eventById(id: Long): Option[EventRow] = { val action = events.filter(_.id === id) val results = db.run(action.result.head) val notFound = None: Option[EventRow] try { Some(Await.result(results, Duration.Inf)) } catch { case e: Exception => Logger.info(s"Failed to...

What is the difference between LOG.error(“IOException: ” + e.getMessage(), e); and LOG.error(“IOException: ” +e.getMessage());?

java,logging,exception-handling
I have observed that both the statements are valid. What is the extra thing logged in the first statement compared to the second one?

Handling RuntimeExceptions in certain circumstances valid?

java,exception-handling,user-input
As I understand it from several tutorials, RuntimeExceptions are actually not supposed to be caught, because they shall reveal inappropiate usage of methods, especially APIs, correct? Furthermore, one might assume that the program is not able to recover from RuntimeExceptions. Now, I experienced a case where I might receive an...

Don't know where exception was thrown using google-test

c++,exception,visual-studio-2013,exception-handling,googletest
We are using Google Test as our C++ unit testing framework. But I ran into a painful situation and don't know how to deal with. Basically, when there is an uncaught exception in the code, I got the following error message printed in the console and get a FAILED. Obviously,...

How to remove duplicate rows with foreign keys dependencies?

database,postgresql,exception-handling,foreign-keys,plpgsql
I'm sure this is common place, but Google is not helping. I am trying to write a simple stored procedure in PostgreSQL 9.1 that will remove duplicate entries from a parent cpt table. The parent table cpt is referenced by a child table lab defined as: CREATE TABLE lab (...

How it can be possible in case of RunTimeException to declare a parent exception in child class?

java,exception-handling
I am referring to Why can't overriding methods throw exceptions broader than the overriden method? but How it can be possible in case of UncheckedException or RunTimeException to declare a parent exception in child class- import java.io.*; class Parent { void msg() throws NullPointerException { System.out.println("parent"); } } class Child...

How can you retry after an exception in Javascript when using promises?

javascript,node.js,exception-handling,promise,bluebird
I'm using the Bluebird promise library. I have a chain of promisified functions like the following: receiveMessageAsync(params) .then(function(data)) { return [data, handleMessageAsync(request)]; }) .spread(function(data, response) { return [response, deleteMessageAsync(request)]; }) .spread(function(response, data) { return sendResponseAsync(response); }) .then(function(data) { return waitForMessage(data); }) .catch (function(err) { // handle error here }); Occasionally...

Handle exception as a parse error in bison

c++,exception-handling,bison
How do i catch en exception thrown upon executing a rule in bison like foo : BAR { $$ = new Bar($1); } The Bar constructor throws std::invalid_argument exception if it's argument is inappropriate. I would like to catch that exception and raise a compilation error, so I get native...

Repeating error message inside a while loop

java,loops,exception,exception-handling
I'm currently working my way through a Udemy Java course and am practicing what i have learnt thus far. I have the following simple program which i am planning on using to get the user to input his name. import java.util.Scanner; public class Adventure { public static final int menuStars...

Java7 multiple exception handling

java,exception-handling,java-7
I have been trying to find out answer to this question but did not get any satisfactory explanation. Here is some background: Java 7 allows us to catch multiple exceptions in a single catch block provided those exceptions are from diffrent hierarchy. Eg: try { // some code } catch(SQLException...

Handle global exceptions in VB

vb.net,exception,exception-handling
Hello I have this project experiencing some problems with what is supposed to be my codes for the "problem" handler. Public Event UnhandledException As UnhandledExceptionEventHandler Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim currentDomain As AppDomain = AppDomain.CurrentDomain AddHandler currentDomain.UnhandledException, AddressOf MyHandler End Sub Sub...

How to re-route exception without marking Exception as handled

asp.net,asp.net-mvc,asp.net-mvc-4,iis,exception-handling
Basically when my app has an unhandled exception I want it to be recorded as an unhandled exception by IIS (so that it can be seen on Event Viewer, for example) but I also want to route the user to an error controller. I've overridden the OnException method of my...

Trying to ouput exceptions to a file - how can I pass objects into catch block?

java,exception-handling,try-catch,jxl
I've got a situation where I'm trying to process a load of rows in a table, and output the result (either success or an exception) to an excel spreadsheet using jxl. The problem is I can't see how to pass the initiated Excel workbook to the catch blocks so that...

Mule - Throw Exception with until-successful

java,exception,soap,exception-handling,mule
This is my mule flow: HTTP => Logger => SOAP (CXF) => Until Successful [JAVA] => LOGGER Spring : <spring:beans> <spring:bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <spring:property name="locations"> <spring:list> <spring:value>test.properties</spring:value> </spring:list> </spring:property> </spring:bean> <spring:bean id="testIntegration" class="x.x.x.IntegrationClass" init-method="init">...

How can I extract ALL the information of the JavaScript native exception?

javascript,exception,exception-handling
Well, as JavaScript is executed in the client-side, I can't control a bunch of environment variables and, at some point, my app will probably throw an exception. What I want to do is to get this exception and make my app fail gracefully and show the maximum information as possible...

How to get details from PyYAML exception?

python,exception-handling,pyyaml
I want to gracefully notify the user exactly where their mucked up YAML file is flawed. Line 288 of python-3.4.1/lib/python-3.4/yaml/scanner.py is where it reports a common parsing error and handles it by throwing an exception: raise ScannerError("while scanning a simple key", key.mark, "could not found expected ':'", self.get_mark()) I am...

Exception handling, only accept specific file inputs

python,input,types,exception-handling,filenames
This is a bit above my pay grade, so I thought I would ask on here. My simple Python code prompts the user to enter the name of a file. However, it must be a specific type of file, or else I would like to throw an error. In this...

Has anyone setup rollbar with Sailsjs?

exception-handling,sails.js
I'm trying to setup the Rollbar.com exception monitoring with Sailsjs. I've reviewed there "Rollbar notifier for Node.js" section. So far I haven't been able to get it running. I'm assuming I need to update the app.js file somehow, but have not seen any errors in startup or logging on Rollbar....

Closing An SqlDataReader that might not have been initialized

c#,exception-handling
I'm stuck in a cycle of different compiler errors and I need some assistance. So case 1: SqlDataReader executed outside of try block allows closing it later, however, leaves the reader exceptions unhanded. var cmd = String.Format("SQL COMMAND HERE"); var command = new SqlCommand(cmd, conSQL); SqlDataReader readerSql = command.ExecuteReader(); //Unhandled...

Input validation (java) using GUI

java,validation,user-interface,exception-handling
I'm creating (well, already created) a loan payment calculator using a GUI in Java. Some of the calculations are wrong and I will fix them, so don't mind those. What I'm really needing help with is the user input validation. I tried using a try/catch block but I keep getting...

Why do Examples of the Repository Pattern never deal with Database Connection Exceptions?

architecture,exception-handling,repository-pattern
I've read a lot of tutorials and seen a lot of code samples regarding implementations of the Repository pattern. In pretty much every case, exceptions that would result from attempting to hit the database when the database is unavailable is not addressed. This seems strange considering that this is a...

How can I modify my PL/SQL procedure to go to my exception handling?

oracle,plsql,exception-handling
I am using SQL developer to write a procedure. The objective is to get the name of the drainage system from one table and get the count of how much the drainage system name code appears in another table. My procedure works, but when I enter an incorrect value, it...

fatfree SQL error handling

php,exception-handling,fat-free-framework
If, for whatever reason, there is an error in creation of an entry using the mapper I get an error. I'd like to do a custom notification and fail gracefully like so... try { $request->save(); } catch (Exception $e) { $this->utils->errorNotify($f3,'could not create a request entry',http_build_query($_POST)); return null; } is...

Handle unexpected exceptions that silently kill a thread

java,exception,exception-handling
I've a thread that sometimes just dies silently and I want to surround the operation with a try/catch block to find out what is going on without killing the thread. I initially surrounded the operations within run with a try / catch (Exception e) block but the concern was that...

Throw Exception, message passed into constructor won't appear in PHP error

php,exception-handling
I have a given class with some methods in it, one of which throws an exception as per the following when certain faulty criteria is met: PHP if ($this->mode !== null) { throw new LogicException('Nem kezdhető új "insert" utasítás.'); } Should I miss enclosing the line with a try ......

What is preventing my event handler method from completing?

c#,wpf,concurrency,exception-handling,event-handling
I'm using a SerialPort, WPF for user interface, a 'ui' object to handle application logic, and a wrapper around SerialPort. The method in question is called when the SerialPort.DataReceived event is fired. It begins to run, then after reading the data, just seems to exit, even though it has tons...

Unique Entity Error message

api,symfony2,exception-handling,doctrine
I have a user entity which have some unique fields. The code bellow shows you how I defined it. /** * @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE") */ ...... /** * @var string * * @ORM\Column(name="login", type="string", length=255, unique=true) */ private $login; Developping an API, I would like to be able to...

Why Application.OnException never runs?

delphi,exception-handling,delphi-xe2,delphi-7
Problem summary: The method assigned to Application.OnException never runs when an unhandled exception occurs. I create a blank project with only this unit and place a single button on Unit.dfm (this is based on an official example) : // Unit1.pas // ********* type TForm1 = class(TForm) Button1: TButton; procedure FormCreate(Sender:...

PHP SeekableIterator : catch OutOfBoundsException or check valid() method?

php,exception-handling,spl,seekableiterator
So I'm not sure if this is buggy design with PHP, or if there is an understood logic to handling inconsistent outcomes for the same interface. The SeekableIterator interface has two methods (seek and valid) that are either in conflict with one another or should be working consistently with each...

Make simple servlet filter work with @ControllerAdvice

spring,filter,exception-handling,spring-security,spring-boot
I've a simple filter just to check if a request contains a special header with static key - no user auth - just to protect endpoints. The idea is to throw an AccessForbiddenException if the key does not match which then will be mapped to response with a class annotated...

Yii2 How to handle Swift_TransportException exception?

exception-handling,yii2,swiftmailer,yii2-advanced-app
When trying to send mail using swiftmailer I am getting the following error: Expected response code 250 but got code "550", with message "550 User [email protected] has exceeded its 24-hour sending limit. Messages to 250 recipients out of 250 allowed have been sent. Relay quota will reset in 1.47 hours....

No LR and SPSR for EL0 in Aarch64

exception-handling,arm,cpu-registers,arm64
In AArch64, There are 4 exception levels viz EL0-3. ARM site mentions there are 4 Stack pointers (SP_EL0/1/2/3) but only 3 exception Link registers (ELR_EL1/2/3) and only 3 saved program status register(SPSR_EL1/2/3). Why the ELR_EL0 and SPSR_EL0 are not required? P.S. Sorry if this is a silly question. I am...

Custom RuntimeException not caught

java,java-ee,exception-handling,runtimeexception
I have my own ApplicationException witch extends RuntimeException: package com.haslerrail.aura.common.exception; public class ApplicationException extends RuntimeException { private static final long serialVersionUID = 1L; private final ErrorCode errorCode; private final Object[] arguments; public ApplicationException(final ErrorCode errorCode, final Object... arguments) { super(); this.errorCode = errorCode; this.arguments = arguments; } public ErrorCode getErrorCode()...

Exception handling in Erlang to Continue execution

exception,error-handling,exception-handling,erlang,ejabberd
What I am trying to do is mochijson2:decode(Ccode) generates any exception or error, program execution should not stop and case branch {error, Reason} should get executed. But when I am trying to get it implemented, it generates error at first line while checking and code doesn't continue execution for lines...

Try until no exception?

python,exception-handling
def foo(): try: html = get(url) while (html is nogood): foo() return html except Exception as e: changeip() foo() The function foo simply returns a good html in text. However, the function sometimes returns None and it's caused when an Exception is caught. So I changed the last line to...

How to get a correctly-chained stack trace for exceptions thrown when handling other exceptions?

java,exception-handling,stack-trace
Suppose I am handling FooException and BarException occurs. Let's assume they are both unchecked exceptions. What I want to see in the stacktrace is: com.bar.BarException: Bar Message at com.baz.BazCode(BazCode.java:123) ... Caused by: com.foo.FooException: Foo Message at com.baz.BazCode(BazCode.java:321) .... Caused by: ... However, by default, all record of FooException will be...

Why is my terminate handler never invoked?

c++,c++11,exception-handling
I have read that one can call std::set_terminate() to use own function as global exception handler, which catches all unhandled exceptions. Simplified code of my program: #include <exception> #include <stdexcept> #include <iostream> void my_terminate_handler() { std::cerr << "Terminate handler" << std::endl; std::cin.get(); std::abort(); } int main() { std::set_terminate(my_terminate_handler); int i...

May I modify the value of an exception inside a std::exception_ptr?

c++,exception,c++11,exception-handling
If I have a exception stored inside std::exception_ptr. I rethrow the exception using std::rethrow_exception, access it using catch(MyException&) and then I modify the value. If I throw the same exception again, should I observe the modification I made? The following code demonstrate my idea: #include <exception> #include <iostream> struct MyException...

Mule - Retry connection with basic flow

java,http,soap,exception-handling,mule
I have a basic mule flow: HTTP => SOAP => JAVA CLASS <mule xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.6.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans...

Java - NoHttpResponseException when using apache fluent api to post

java,apache,exception-handling,fluent,http-request
I am continuously posting data to server using Java with Apache fluent api. Content content = Request.Post(URL) .bodyForm(param) .execute() .returnContent(); The above works perfectly but after some random execution time I am getting org.apache.http.NoHttpResponseException: failed to respond. How I can handle this to post the same parameter again after getting...

Getting Apache Camel to stop retrying if failed to move the file after route completion

java,file-io,exception-handling,locking,apache-camel
The example route below picks up a file and performs a series of operations on them. Once completed, as noted in the camel:from field, the route is instructed to move the file to a .processed directory. Alternatively if failed, move it to the .error folder. The problem occurs when another...

NetworkX, How do I successfully catch network.exception.NetworkXError when node is not in the graph?

python,exception-handling,networkx
When a node is not in the graph I get and exception error. As I try to catch and handle it, I can't (so I must be doing something wrong). How do I catch and handle networkx.exception.NetworkXError? Here is the error: <snip> raise NetworkXError("The node %s is not in the...

Throwing exceptions from Spring REST webservice as JSON/XML

java,spring,web-services,rest,exception-handling
I have a REST web service controller that looks like this: @RequestMapping(value = URIConstants.URL_DOCUMENT_SEARCH, method = RequestMethod.POST, produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) protected DocumentSearchResponse getDocuments(@Valid @ModelAttribute DocumentSearchRequest objDMSRequest,BindingResult bindingResult, HttpServletRequest objServletRequest) throws AppException { if (bindingResult.hasErrors()) { //I want to throw my custom exception here ///Or can anyone suggest...

Error is not thrown inside a deferred method

node.js,exception-handling,deferred
Can somebody explain to me why my error is not thrown in my first example? And why it is when I use process.nextTick() ? var deferred = require('deferred'); // This code does not work. // Error seems to never been thrown and script kind of freeze without saying anything. deferred.resolve().then(function(){...

python raising an error exception

python,exception,error-handling,exception-handling
I am working on an othello game for class and am trying to raise an exception when the player makes a valid move but this exception is making my program crash and im not sure why. I get the error: Traceback (most recent call last): File "C:\Users\chapp_000\Desktop\Othello\OthelloUI.py", line 46, in...

Finding exception (PL/SQL)

oracle,plsql,exception-handling
I am running a code in Oracle that asks the user to input a route type, and then the program fetches the longest and shortest routes depending on the user-input route, as well as the number of rows fetched. I need to add any exception to the code and I...

Handling exceptions in asynchronous socket callbacks

c#,sockets,exception-handling,backgroundworker
I've been trying to get my head wrapped around socket communications and I've put together a small Windows Forms application as a test. This is basically a client that will connect to a server, send some bytes and disconnect. Ultimately, I'll receive a response from the server, too, but I've...

Exception handling when using Python's subprocess.Popen

python,exception-handling,subprocess
When dealing with open files, Python has the with syntax that makes sure the file closes when leaving the block - regardless of exceptions etc. with open('foo.txt') as f: foo = f.read() Since processes are resources too, I was wondering: is something similar possible or recommended when using Popen? For...

Removing infinity values of a function using exception handling, *args, and **kwargs

python-2.7,exception-handling,args,kwargs,gradient-descent
I'm currently working through the book Data Science from Scratch by Joel Grus, and I've run across a function that I don't really understand: def safe(f): def safe_f(*args, **kwargs): try: return f(*args, **kwargs) except: return float('inf') return safe_f The safe function is called within a Gradient Descent algorithm to remove...

Throw and Catch Custom Exception

java,file,exception,exception-handling,fileopendialog
I have a method to load a customer file by choosing it from the File Open Dialog Box and it works, except for when I click the Cancel button. It still loads the selected file even if I press the Cancel button. I want to load a Custom Exception if...

Safe fire and forget method in Perl

multithreading,perl,exception-handling,thread-safety
I need to execute a method (not process) asynchronously in my Perl code, but I must ensure that this code will never raise any exception and stop my main task execution. What would be the best way to call a method asynchronously and silencing any potential exception whether it is...

multiple exception handler in python

python,exception-handling
I'm writing code that has to deal with a lot of IndexError exceptions. So, I used a try except block: try: <do some level_1 calculations> except IndexError: <change to level_2 calculations> But, what if my exception-handler again raises another IndexError? How can I safely put another IndexError exception with this...

Java: Why Program Skip Char Input?

java,exception-handling
Java Skip First Character Input When Program Catch the Exception? System.out.println("Enter Character:"); f = s.next().charAt(0); Program Code: public class Main { public static void main(String[] args) { int num; char f = 'y'; Scanner s = new Scanner(System.in); do { try { System.out.print("Enter Number:"); num = s.nextInt(); catch (InputMismatchException e)...

Handling Keyboard Interrupts

sockets,exception-handling,sml,smlnj,keyboardinterrupt
I've got a minimal TCP server running in the SML/NJREPL, and I'm wondering how to gracefully close the listener socket on a keyboard interrupt. A stripped-down version of the server is fun sendHello sock = let val res = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello world!\r\n\r\n" val slc = Word8VectorSlice.full (Byte.stringToBytes res)...

trap exceptions comprehensively in Jython

exception,exception-handling,jython,throwable
This is my attempt so far to trap all exceptions in Jython code. The most difficult thing, I find, is trapping exceptions when you override a method from a Java class: with the "vigil" decorator below (which also tests whether the EDT/Event Despatch Thread status is correct) you can find...

How do I throw an Exception from inside a Parallel.ForEach loop?

c#,foreach,exception-handling,parallel-processing
I have a Parallel.Foreach loop which downloads files like so: try { var parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = 8; int failedFiles = 0; Parallel.ForEach(FilesToDownload, parallelOptions, tile => { bool downloaded = DownloadTile(File); if (downloaded) { //Downloaded :) } else { failedFiles++; if (failedFiles > 10) { throw new Exception("10...

Android Exception: UnknownFormatConversionException

android,exception,exception-handling,format
Hi I am setting some text inside a RobotoText that is positioned inside of a ViewHolder I am calling it like this: viewHolder.txtSimilarAds.setText((((Property) ads.get(position)).getSimilar_items_count() == 1 ? context.getString(R.string.ad_data_similar) : context.getString(R.string.ad_data_similar_plural, ads.get(position).getImagesCount()))); However (sometimes NOT always)for some reason I keep getting this error exception UnknownFormatConversionException and it points to this line...

“The Parameter Is Incorrect” MFC exception

c++,exception-handling,mfc
This is native C++. No .NET framework involved. I am trying to figure out which exception is thrown when the CListBox gets an invalid parameter. Turns out MFC uses this exception quite a lot but I can't determine the actual exception type thrown. I have tried a lot of different...

RedirectToAction when NullReferenceException of the Model is raised

asp.net-mvc,exception-handling,asp.net-mvc-5
I have the following controller method public ActionResult Details() { try { Pacient pacientdp = new Pacient(); if (pacientdp.PacientPrenume == null) { return RedirectToAction("Index", "Home"); } var id = WebSecurity.GetUserId(User.Identity.Name); MedicalDBContext pacientContext = new MedicalDBContext(); Pacient pacient = pacientContext.Pacients.FirstOrDefault(x => x.PacientID == id); return View(pacient); } catch (Exception ex) {...

Unhandled exceptions and background workers

.net,exception-handling,backgroundworker
In our application we use several background workers which are executed using SERVICENAME__bgw.RunWorkerAsync() where SERVICENAME is one of several different background worker processes executed by different timers. We recently saw this error message that was shown after an unhandled error bubbled up to the top of the call stack: My...

How to handle exception between spring REST web services

java,rest,exception-handling,spring-boot
I have two web services based on Spring boot, REST and MVC. The first service(DesignService) project calls the second service(UserService) project passing a email as parameter and gets the user object(User.java) back. How can I handle if no user is found. DesignService project repository.java @Autowired RestTemplate restTemplate; getUser(String email){ restTemplate.postForObject("url...

Does Java declare “throws Exception” by default?

java,exception,exception-handling
Consider following classes: class X { public void met() { } } and class Y extends X { public void met() throws NullPointerException { throw new NullPointerException(); } } From what I have read on other questions ( Why can't overriding methods throw exceptions broader than the overriden method? and...

Why can an Exception not be rethrown in the BackgroundWorker RunWorkerCompleted event

c#,asynchronous,exception-handling,backgroundworker
I've checked through some posts on this topic which cover how to get around this issues, but I can't quite understand the Why of this odd behaviour? Short version: Why is are Exceptions thrown inside the RunWorkerCompleted event not caught by the calling code? Detailed version: I have a BackgroundWorker...

Globally applied custom exception filter is not triggered when error is thrown by a method called in the constructor of my base controller

c#,.net,asp.net-mvc,exception-handling
I have this custom exception filter: public class CustomExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext filterContext) { try { if (filterContext == null) return; // Log error details to the DB } catch { // Intentional empty catch } } } Which is applied globally in RegisterGlobalFilters (which is called...

Why doesn't Application_Error in my global.asax catch the “500:Internal server error”?

asp.net,exception,exception-handling,global-asax
When a response is returned with StatusCode (500), the Application_Error sub in my Global.asax is not being fired.

How to access exception in Camel errorHandler?

java,exception-handling,apache-camel
Use Case I'd like to log unhandled exceptions for a particular route in Camel in a reusable manner. Specifically, I'd like to extract enough information from the exception and write it to the database, which is then read by some monitoring software. Through the use of a dead letter queue,...

Seemingly unhandled exception in a generator with threads involved

python,multithreading,exception,exception-handling,generator
Consider the code below. The intention is to have a generator that manages a thread. The thread is responsible for sourcing data, pushing onto a fifo of size one, which the generator pops from and yields. It runs fine normally, printing out an ever increasing integer, interleaved with close thread...

Is it safe to use an exception outside the catch statement if it is held in a std::exception_ptr?

c++,exception,c++11,exception-handling
I have a std::exception_ptr with an exception inside it. I am going to invoke std::rethrow_exception to get the actual exception, will the exception be valid after the catch statement? My guess here is that since I still hold the std::exception_ptr it will still be valid. See the example: std::exception_ptr ePtr...

Can C++ disambiguate the type of an exception object?

c++,exception,exception-handling
With empty exception objects such as, class E1 { }; class E2 { }; Can C++('s compiler or the resulting executable) safely disambiguate between such exception objects in a catch statement? If so, does it mean that a type code for each exception object should be stored and tracked internally?...

Java - How to keep running on exception

java,exception,exception-handling
This question seems pretty simple. How do I keep running my application on an exception. For instance how would I go about doing this. Server application tries to run on port 1234, but it's not available. Normally it would just crash. But how can I make it keep running and...

Play: How to improve error handling and avoid creation of unnecessary throwable instances

scala,exception-handling,playframework
Creating and throwing exceptions is an expensive task... and often in web applications is not necessary to throw exceptions at all. If an error occurs in a service class used by the controller, then throwing an exception makes sense... but if the controller is already aware of the issue (e.g....

Best way to handle exceptions that can not occur

java,exception-handling
I use the following Code to build an SQL Statement that updates the values of the fields which a specific object has. My question is, since I check if the object has a specific field the exception can never occur. What is the best way to make this code more...

Does jni::ExceptionDescribe implicitily clear the exception trace of the JNI environment object?

java,c++,exception-handling,jvm,jni
I tried to implement some kind of exception handling At first i called jni::ExceptionDescribe() after that i used the implementation of How to obtain a description of a Java exception in C++ when using JNI? which i just named for simplicity printStackTrace()and which completely works fine . My problem is...

Python twisted not catching exception

python,exception-handling
My main class is something like # file bmdaemon.py from txjsonrpc.web import jsonrpc from twisted.web import server, xmlrpc from twisted.internet import reactor, defer, threads, task import xmlrpclib from txjsonrpc.web.jsonrpc import Proxy class BMDaemon(jsonrpc.JSONRPC): # class definition class XmlRpcInterface(xmlrpc.XMLRPC): # class definition if __name__ == "__main__": try: bm_daemon = BMDaemon() xml_interface...

Dealing with in a finally block [duplicate]

java,exception-handling,try-finally
This question already has an answer here: java try finally block to close stream 7 answers I have some code which creates a JarFile and a URLClassLoader, both of which I want to close at the end. Naturally, I decided to use the finally block to deal with the...

C - Windows Exception Handler Invalid Handle

c,windows,winapi,exception,exception-handling
I have a problem about managing an exception. In my code I put hIn = INVALID_HANDLE_VALUE to test the exception, and "null" is a non existing file. My piece of code is __try { hIn = CreateFile (_T("null"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); hIn = INVALID_HANDLE_VALUE; ReadFile (hIn, buffer,...

ArrayIndexOutOfBoundsException: 1 in web server

java,exception-handling
I have made a simple RESTful web service using tomcat web container and jersey library. I have overridden only post method, rest all default settings are used. While sending POST query from curl from server machine I get expected response. From other machine also, I am getting expected response for...

Why does Python throw a KeyError when accessing an unset property?

python,exception-handling,keyerror
What are the rationale and implications for throwing KeyError instead of returning None when accessing an unset property on a Python dictionary? I know that language design involves trade-offs, some of them based on practical concerns and some based primarily on philosophy. From a computer science perspective, why has Python...

Can't figure out how to deal with these errors [duplicate]

java,swing,exception-handling,nullpointerexception,thread-safety
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers i built a little software. The software runs perfectly ok as it should. On initiation of the software, a option pane pops up asking for name, user can...

Exception handler in Node.js

javascript,node.js,exception,exception-handling
I have a very simple question; I have a wrong endpoint and when I try the following code, it throws an exception client.post("http://WrongEndPoint", [], function (data, response) { console.log("data:", data, "response:", response.statusCode); }) ERROR: events.js:72 throw er; // Unhandled 'error' event ^ Error: connect ETIMEDOUT at errnoException (net.js:905:11) at Object.afterConnect...

Returning an integer to determine which switch statement to show

c++,exception-handling,switch-statement,user-feedback
I'm creating a board game (stratego) in c++ and was wondering if it considered a poor practice to return an integer from a class method in order to determine which case in a switch statement to show to the user. Example: In stratego, you can't attack board pieces that are...

Aggregate runtime exceptions in Java 8 streams

java,exception-handling,java-8,java-stream
Let's say I have a method which throws a runtime exception. I'm using a Stream to call this method on items in a list. class ABC { public void doStuff(MyObject myObj) { if (...) { throw new IllegalStateException("Fire! Fear! Foes! Awake!"); } // do stuff... } public void doStuffOnList(List<MyObject> myObjs)...

Rails External Service Exception Handling

ruby-on-rails,ruby-on-rails-4,exception-handling
I am connecting my application to a third party API to pull and push data. One thing I'd like to do is implement some exception handling so my users will receive a related error message if something happens with the API. I have a show action that has the main...

Java Character Input With Loop?

java,loops,exception-handling
Guys I want to write a program which find Nominator and Denominator with Exception Handling and calculate their result. I also added a Simple Interface which is Would you like to continue press 'y'. or 'n'. Character is in Lower Case. I Want that Interface Occur only on two things.When...

Java: unhandled exception

java,eclipse,exception,exception-handling,try-catch
I would like to handle an exception but the Eclipse editor is giving me tips which I'm not understanding. This is the method's code: public Collection<String> listOfFriends(String codePerson) throws NoSuchCodeException { Collection<String> s = new LinkedList<>(); try { people.get(codePerson).getFriendsCodes().forEach( code -> s.add(getPerson(code))); } catch (Exception e) { e.printStackTrace(); } return...

Handling 500 Internal Server Error from DomDocument in Laravel 5

php,laravel,exception-handling,laravel-5
The library I wrote for Laravel uses DomDocument. I use this library under my Controller, and its namespace is app/Services/Verify/. The library gets initialized and used when I put it some inputs into a form. When the library fails, Laravel would fail the way it would - returning the following...

cancel task.delay without exception or use exeption to controll flow?

c#,asynchronous,exception-handling,async-await,task-parallel-library
I'm unsure about two possibilities to react to an event in my code. Mostly I'm concerned about which one needs less resources. I have a method with an observer registered to an eventproducer. If the eventproducer returns something, the method exits and the caller of the method starts the method...

Is there any other role of throws instead of propagating a checked Exception?

java,exception-handling,propagation,throws,checked-exceptions
After studying more and more about throws statement in Exception Handling I am getting confused.I found- If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. class Boxing1{ public...

Proper use of custom exceptions

c#,exception,exception-handling
I'm creating a function and want it to be able to give meaningful error message whenever it encounter an error. I would like to ask whether this situation is a proper use of custom exception, and if not what is appropriate way to handle it. Example : int res =...

Laravel 5 - How do I handle MethodNotAllowedHttpException

php,laravel,error-handling,exception-handling,laravel-5
Where do I catch MethodNotAllowedHttpException exception in Laravel 5. In laravel 4 i can do this in start/global.php

make a value zero if exception list index out of range

python,list,exception-handling
I'm doing some calculation in python and I have to sum items from a list, if they are on the list. This is the code: Ei=-J*S[i][j]*(S[i+1][j]+S[i-1][j]+S[i][j+1]+S[i][j-1]) what I want is to make zero the value of the element that gives the error list index out of range. Is there a...

How to call code inside try block one more time if exception is thrown?

python,exception,exception-handling
I am new to python and I am writing code that uses OAuth to authenticate and when the token expires after 60 minutes, it needs to get a new one. try: if uploadedContent is not None: thing.action(uploadedContent) except LoginOrScopeRequired: print("Logging in...") set_access_credentials({"identity", "submit"}, get_access_token()) I currently have this code to...

How to write an exception in the following case in Python3?

python,exception-handling
I need to revise a python code (given by a programmer) which I would like to use for a genealogy project of mine. I am very new to python and start being able to read code. Yet, I do not know how to fix the following thing. I get the...

Difference between catch vs catch and rethrow exception in java?

java,exception-handling
We can throw exception by try-catch or throw Scenario 1: public void testMethod() throws MyException { throw new MyException(); } Scenario 2: public void testMethod() throws MyException { try { throw new MyException(); } catch(MyException e) { throw e; } } In the above code block Do we really want...

exception is not coming with sql max function

oracle,plsql,exception-handling,oracle11g,max
I wrote the below query expecting NO_DATA_FOUND exception to be thrown when no rows found. BEGIN SELECT MAX(A_id) + 1 INTO id_variable from table_A; EXCEPTION WHEN NO_DATA_FOUND THEN SELECT MAX(A_id) + 1 INTO id_variable from table_A_archive; END; there is no data in table_A but no exception was thrown and eventually...

Why can't SyntaxError be caught by user code? [duplicate]

python,python-2.7,exception-handling
This question already has an answer here: Failed to catch syntax error python 2 answers I want to catch every program error so that I can display those errors in my GUI program, but I find I'm not able to catch certain kinds of error like SyntaxError and IndentError....

How do I successfully use the Thread.sleep() method in Graphics?

java,exception-handling,applet,awt,thread-sleep
This is my code so far: // Imported Classes public class Timer extends Applet { public void paint (Graphics page) throws InterruptedException { Thread.sleep(1000); } } I just want to know how I can get this to work. I've used the Thread.sleep() method in other code before, but never with...

Exception Handling: What level to put it at

python-2.7,exception-handling
This is a bit of a general and conceptual question, not sure if it is in scope for SO, but I'll give it a shot. I've run into situations like the following several times and I've never been sure how to handle it. I have several functions that call each...

How to prompt programmers to use try except clause in python?

python,exception-handling,static-analysis,pylint,try-except
Let's say I have a methodA that raises an exception: def methodA(x, y): if y != 0: z = x / y return z else: raise ZeroDivisionError("zero can not be a denominator") And in methodB I called methodA without handling the exception: def methodB(x, y): print methodA(x, y) Here I...

Throwing exceptions from JBPM WorkItemHandlers?

exception-handling,jbpm
I'm a little confused about the subject of throwing exceptions from JBPM work item handlers and handling the exception elsewhere in the business process. We're using JBPM 6.0.3 to run in Jboss EAP 6.1. The JBPM User Guide implies that you should never throw exceptions from within a WorkItemHandler. Instead,...