FAQ Database Discussion Community


Simple fix with Throw Catch OO WPF

c#,wpf,oop,try-catch
Situation I have an issue with a try catch In an OO WPF application I'm developing that allows Members of different types to join Races. Problem To put my problem in laymans terms, I'm trying to get a Member to join a race with the following code: race.joinJunior((JuniorMember)hillracing.searchMembers(Username)); so, a...

Python: Multiple try except blocks in one?

python,try-catch,except
Is there a neat way to have multiply commands in the try block so that it basically tries every single line without stopping as soon as one command yields an error? Basically I want to replace this: try: command1 except: pass try: command2 except: pass try: command3 except: pass with...

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...

Try catch never enters catch block

sql,try-catch
The problem with the code below is that I never see my catch code execute. If my id doesn't exist, it shows a empty datagrid. What goes wrong? private void btnSearch_Click(object sender, EventArgs e) { try { this.Cursor = Cursors.WaitCursor; SqlConnectie vandaag = new SqlConnectie(); vandaag.Connection(); SqlDataAdapter sda = new...

for - try combined loop?

java,for-loop,try-catch
Working with some legacy code, and encountered this: File file = new File() File[] files = file.listFiles(); for(int i=0;i<files.length;i++) try { { System.out.println("Do stuff"); } } catch (Exception e) { e.printStackTrace(); } it compiles and runs, but I don't know which loop is inside the other, or why it works....

if condition with float text issue

java,android,if-statement,try-catch
i did an app on android studio to get the result for multi-text depend on specific calculations , but i have a problem with float in my edit text, the user have the choice to input number in the text or leave it empty, so when he press on the...

Java while loop endlessly catching mismatch exception

java,loops,exception,while-loop,try-catch
I'm trying to create a simple while loop in java that asks the user for a number and stores it in a variable. I'm also checking to make sure the value they entered is a number. The loop should tell the user that they did not enter a number if...

Not allowed try catch block for basic input computation

java,try-catch
If ENTER is inputted, i.e. null or empty string, the following error is thrown. Can't seem to work around it. Exception in thread "main" java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842) at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.lang.Double.parseDouble(Double.java:538) at com.company.Main.main(Main.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at...

Have exception hit two except blocks in python

python,exception,try-catch
Here is an example of something I want to do in code: class MyClass(object): @classmethod def test_func(cls, x): try: return cls.cache[x] except AttributeError: cls.cache = {} except (AttributeError, KeyError): cls.cache[x] = "CACHE STORE" return cls.cache[x] The idea here being my class will cache some results based on an input x....

Java catch error not working on second iteration of loop

java,exception,for-loop,try-catch
I have a nested try > catch situation where the inner catch inside a loop is checking for a possible expected exception. All this works fine for the first iteration of the loop. If a duplicate is found it is reported and it moves on to the second time round...

Converting char * to CString inside a catch block in a UNICODE application

c++,unicode,mfc,try-catch
I have this code inside an MFC application: catch(cv::Exception &ex) { USES_CONVERSION; MessageBox(A2T(ex.what()), _TEXT("Error"), MB_ICONERROR); } But I am getting this error: error C3204: '_alloca' cannot be called from within a catch block How can I fix this error? The poriginal solution for converting const char * to CString was...

In Python's try… else… clause, why is the else claused parsed if try fails?

python,try-catch
I'm coming across an issue with try... else... I'm testing that a variable has been set using try. If it has not been set, I just want to continue with the loop. If the variable has been set, I want to run the else part. However, Python throws a wobbly...

Passing array value to URL shorten method throwing an exception

google-apps-script,try-catch,url-shortener,google-url-shortener
Am trying to pass array of values to the url shorten method and am getting the shorten form of the url, but the problem is, even though am getting the output, the exception is throwing in the catch block(Exception: Invalid Value). i dont know why it happening. can someone please...

JProgressBar Doesn't Start Until Try-catch finishes

java,api,try-catch,gson,jprogressbar
I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment. I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it? kazananiBelirleButon.addActionListener(new ActionListener() {...

checking if an input of an integer is a string with try catch

java,try-catch
I want the try-catch to loop until i input a proper integer, but all i am having is an infinite loop when i enter a string : public class Main00 { static Scanner scan = new Scanner(System.in); static int c = 1; public static void main(String[] args) { int num...

Java, using throw without try block

java,exception,try-catch,throw
For the following method, is it okay to throw the exception when it isn't inside a 'try' block? public void setCapacity(x) throws CapacityExceededException { if (x > 10) throw new CapacityExceededException(x); else this.x = x; } ...

Python – Breaking out of a deeply nested loop with `while`, `try`, `if`, and `except` statements

python,if-statement,while-loop,nested,try-catch
Here is my code that solves a quadratic equation given user inputs a, b, c. However, I want to check for incorrect user inputs. If a user inputs anything but a float, the user is confronted with print "Not a valid input. Try again.\n" followed by a loop of the...

try/catch block not working in actionlistener

java,user-interface,try-catch,actionlistener,jtextfield
I am working on 2 programs for school, one to take contact info and save it to a text file and the other is to read from the text file. All works perfectly but I have to add a try/catch block the program that takes input so that it would...

how to use try and catch to print out the unknown error message when calling a function in general in matlab

matlab,error-handling,try-catch
This is the code try ** = myfunction( ~ ); catch e % how shall I do to print out the unknown message ? end I encounter this during a project. I already fixed the error. But I was still confused a bit without an answer. So I post it...

Use of Try Catch Block with ELMAH

c#,try-catch,elmah
Since ELMAH logs UNHANDLED exceptions and I want to log all errors via ELMAH, does that mean I should not be using try-catch block anymore anywhere on my code? If I do not use it, it will show the yellow screen of death, which I believe I can be handled...

In C#, why is a variable not definitely assigned at the beginning of a finally block?

c#,try-catch
I don't understand why the following code produces an error. Normally I can figure things out from the language specification, but in this case I don't understand the language specification. This isn't causing problems in my code, by the way, I just want to understand the language. Example: bool success;...

Preventing the user from entering identical elements(within a malfunctioning try catch)

java,if-statement,arraylist,try-catch
So the following code is like a simple game,where the objective to to guess the correct numbers(which are 1 to 5).Anything else is incorrect and the user is given a warning message if they enter similar numbers.The comments would explain the loops and variables declared. The only problem I have...

where should i catch the exception???? main public method? or private method? [closed]

java,try-catch
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.util.HashMap; import java.util.Map; import javax.management.JMX; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.openmbean.CompositeDataSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tuniu.myMonitor.dataCollection.IDataCollection;...

Is it a good practice to put ResultSet into a nested try-with-resources statement after Java7?

java,jdbc,try-catch,try-with-resources
According to doc of http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#close() , When a Statement object is closed, its current ResultSet object, if one exists, is also closed. But accoring to Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards? , it is seems to be a good practice to explicitly...

Adding return in finally hides the exception

java,exception,exception-handling,try-catch,try-catch-finally
I have the following code public static void nocatch() { try { throw new Exception(); } finally { } } Which gives the error Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type CustomException Which is as expected, but adding a return statement in the finally block makes...

Delphi FTP timeout exception

delphi,exception,ftp,try-catch,indy
I'm using Indy's FTP. It works perfectly with what I want, my only issue is that if the system isn't connected to the Internet or the server is down then it displays a TimeOut exception on screen. I can't seem to be able to find out how to catch the...

Exception is not bubbling up

c#,exception-handling,try-catch
I'm trying to catch a thrown Exception, but it doesn't bubble up to where it was called. It breaks in InsertNewUser's catch block, saying "An exception of type 'System.Exception' occurred in PeakPOS.exe but was not handled in user code" If I click on debugger Continue, it goes to some file...

Java - Will try-with-resources call .close() if the user closes the program unexpectedly?

java,sockets,resources,try-catch
I'm working on some server code for a program I'm developing and I'm using try-with-resource statements to close the sockets. try ( ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); ) { out.println("This is the server! Hooray! :D"); } catch (IOException e) {...

where should we use commit(session), in try or finally?

java,hibernate,exception,try-catch
If I want to use commit(session) after successful execution of database operation, where its better to put it in try or in finally block ? Here I used it in finally, should it be in try ? public void delete( --- ) { Session session = init(); try { ----...

Parse XML catch block not catching exception in JS

javascript,jquery,ajax,xml,try-catch
I have a function that takes an XML file (obtained via AJAX) as input, parses it as XML and then execute some functions on it. A stripped down version can be found below. AJAX $.ajax({ type: "GET", url: "./default.xml", dataType: "xml", success: function(data) { parseMech(data); } }); parseMech function function...

Try statements (Python)

python,oop,try-catch
I recently discovered the trystatement (I'm pretty new) and I know about except, but I have some questions: 1) How do I use finally? 2) Can you have multiple excepts with different errors? Could you give me some examples of this? ...

How can I create a catch that ensures nothing other than a number is entered into a textbox but also accepts a blank entry

c#,wpf,textbox,try-catch
I have a textbox. The lecturer says I must have a catch to ensure nothing other than a valid number is entered but the textbox is optional. In other words the user might not make an entry at all. I have a catch for it that catches any letters entered...

PHP try catch block does not catch

php,file,exception,try-catch
I want to open a file in PHP, but to be sure that this file exists, I wanted to put it inside a try catch block, so the script does not collapse. If the file does not exist the script is supposed to stop. This is my code which should...

not avoiding/skipping errors with try and tryCatch

r,for-loop,error-handling,try-catch,nls
I have a nlsLM inside a for loop because I want to try different start values to fit my data. I already know that some start values generates this error: singular gradient matrix at initial parameter estimates, but I want to skip this error and continue with the loop, fitting...

How to handle catch block with functions?

java,error-handling,try-catch
I'm curious to know, Suppose i've a function says myFunction(). Take a look into this sample: public void myFunction() { try { for (int i = 0; i <= 15; i++) { System.out.println("Counting: " + i); } } catch (Exception e) { e.printStackTrace(); } } Now if any kind of...

Return string from try catch block

java,android,http,try-catch
I'm trying to return string from Foo function, but it application crashes. public String Foo (String email){ String url_set = "http://****.php?email=" + email; String responseStr = "1"; try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_set); HttpResponse response = httpClient.execute(httpPost); return responseStr; } catch (UnsupportedEncodingException e) {...

Try, catch and Exception handling [closed]

java,exception,try-catch
Test class: package learning; import java.io.IOException; import java.util.Scanner; public class Test { static Scanner user = new Scanner(System.in); public static void main(String[] args) { Test2 t = new Test2(); try { t.run(0); } catch (Exception e) { try { t.run(user.nextInt()); } catch (Exception ee) { try { t.run(user.nextInt()); } catch...

How to throw an exception if parsing with Long.parseLong() fails?

java,exception-handling,try-catch
I am trying to write some kind of a stack calculator. Here is a part of my code where I am handling a push command. I want to push integers only, so I have to get rid of any invalid strings like foobar (which cannot be parsed into integer) or...

Java Throwing Custom Errors

java,error-handling,try-catch
So I've been working with Java for a little while now. I technically am still new to the language. I have created a couple custom errors for a personal project I'm working on and I was wondering if there was anyway to use the methods that throw these errors without...

python input check function not being called properly

python,return,global-variables,try-catch,raw-input
I'm working on a very simple temperature converter in Python (just for practice), and am struggling with some of the UX components. I'd like to have checks in place to continue prompting for variable input when invalid entries are made. My full code is below: o_temp = '' def temp_input(o_temp):...

While - try - catch in Java

java,while-loop,try-catch,numberformatexception
I need a java program that ask a number between 0 and 2. If the user write 0, the program ends. If the user write 1, it executes one function. If the user write 2, it executes another function. I also want to handle the error "java.lang.NumberFormatException", with a message...

For line in file not working with try/except

python,python-2.7,for-loop,try-catch
I'm running in an issue trying to replace pipes with commas in a text file. try: replacement except NameError: for line in dataTable: newdata = line.replace("|", ",") output.write(newdata) print "NO COMMAS FOUND IN " + tableLoc + "." The print statement works fine, when I try the "for line in...

How to make Android Guessing Game to restrict the number of guesses to 3 attempts after which a message will be displayed

java,android,if-statement,random,try-catch
I need to make the android guessing game I have so far to have a limit of 3 attempts after which the message like game over will be displayed, however I have no idea how to do it as I'm still new to programming so I would appreciate your help...

Can MatLab 'catch' be at higher level than 'try'?

matlab,try-catch
Is it possible in MatLab to throw an exception in a nested function, and have it 'caught' by a higher up function, such as in C++ or Visual Basic?

When I create a class, I receive “illegal start of type” error in “try-catch” block

java,try-catch
class address { String address; String newaddr = address.trim(); final int ziplength =4; String input; Scanner in = new Scanner(System.in); String temp = in.next(); String zipcode = input.substring(input.length()-ziplength); try **//illegal start type error** { Integer.parseInt(zipcode); System.out.println("PO is: "+zipcode); } catch( Exception e) **//illegal start type error** { System.err.println("Last 4 chars...

Scala try and catch Error

scala,try-catch
So here is my code: def loadOperation(fileName:String): csvList = { try{ val pattern = """^(.+);(\d{5});(4|2|31);(0|1);(.+);(\d+|\d+,\d+)$""".r Source.fromFile(fileName).getLines().foldLeft(List[CsvEntry]())((csvList, currentLine) => currentLine match { case pattern(organisation,yearAndQuartal,medKF,trueOrFalse,name,money) => new CsvEntry(organisation,yearAndQuartal.toInt,medKF.toInt,trueOrFalse.toInt,name,money) :: csvList case default => csvList }) } catch { case one: java.io.FileNotFoundException => println("This file...

What is the value of letting an exception move up the call stack?

java,exception,try-catch
I was just reading about try-catch blocks and exception handling, and I read something in the "Propagating IOExceptions" section that confused me a bit. Jenkov says that if Method C throws an IOException - public void MethC() throws IOException{}- but does not have a try-catch to handle it, it will...

How can I avoid poor program performance from a TRY statement?

c#,opengl,try-catch,game-engine,opentk
I am currently developing a basic voxel (cuboid) game engine, and I have encountered a performance issue. Every frame the game: Finds player's viewing direction → Checks every co-ordinate in the player's direct view path → Finds closest occupied space → Draws a wireframe around this block. I am using...

Bad practice to continue with value set in catch block?

c#,exception-handling,try-catch
I am using something like this in my code: //some code that gets the group, etc. Point3d rotationPoint; try { rotationPoint = GetRotationPoint(group) // Throws NoDataFoundException } catch(NoDataFoundException) { rotationPoint = RequestRotationPoint(); // Let user pick the rotation point instead } //...and then simply continue the method The reason for...

Handle services returning Try values in Spray

scala,try-catch,spray,spray-dsl
I am working on a codebase where calling my Spray API need to synchronously call a service that returns a Try which Spray need to format and return over HTTP. My initial attempt looked like this : // Assume myService has a run method that returns a Try[Unit] lazy val...

How to know what to catch with Try/Catch Block

java,try-catch
I'm simply trying to read in a text file with BufferedReader, and I'm using a try-catch block that is suppose to catch any IOExceptions. I thought it did, and even added a FileNotFoundException in case that was the problem. Yet I'm still getting : Error: unreported exception java.lang.Exception; must be...

Why is the catch statement being ignored here?

java,try-catch,stack-trace
This is practice code from a book and i'm learning about try/catch statements. The first method shown calls for the load method an retrieves two images. The error in this code is that the name of the first img in the resources file is called "welcome.png" but as you can...

How do I catch Selenium Errors using WebDriverJS

javascript,selenium,selenium-webdriver,try-catch
So I am using the JavaScript implementation of Selenium, WebDriverJS. As with any web browser automation the biggest hurdle is getting the code slow down long enough for page elements to load. My solution is this: for each element I want to interact with I have a code block like...

Trying to add try and catch to code, stuck

java,try-catch
I need to implement a try and catch around 2 blocks of code. each need there own. code that I have written. I have made a class for it: public boolean makeOffer(int offer) throws OfferException { // reject offer if sale is not open for offers if (this.acceptingOffers == false)...

How do IDE's “know” when an object needs to be in a try/catch block?

java,eclipse,exception,intellij-idea,try-catch
Sometimes when I'm coding in Java I will forget to put some code in a try/catch block. Both Eclipse and IntelliJ Idea warn me to put it in a try catch block or make the function throw an exception. My question is, how do the IDE's recognize when my code...

C++ exception handling and template

c++,try-catch
I'm new to C++ and have this assignment about exception handling and templates that is giving me problems. I can't figure out why my catch isn't working. I'm getting "error: expected unqualified-id before ')' token. Can someone correct this problem and explain why I'm getting this error? Thanks to all...

Python DBusGMainLoop inside thread and try and catch block

python,multithreading,try-catch,keyboardinterrupt
I'm currently trying to create a python script which has to use the GObject.MainLoop() to communicate with a Bluetooth client. I put the loop in a new thread in order to not block the remaining code. Everything works fine until I've tried to quit the program with Control + C....

Java run code only if no exception is thrown in try and catch block?

java,exception-handling,try-catch
How do I make it so the code runs only if there was no exception thrown? With finally code runs whether there was an exception or not. try { //do something } catch (Exception e) {} //do something only if nothing was thrown ...

Try-Catch block getting length of string error

java,try-catch
I have everything working but I am having an issue with the JTextField. When the user submits nothing, it should be returning null rather than 0. So far it's returning 0, but I need it to return NULL. It's not reaching the Catch block at all even if I put...

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...

Implementing a try/catch block in php constructor function

php,laravel-4,try-catch
I have a query with try-catch block. I am going to create object and if it fails it will throw error message or say redirect on some other page. Code function __construct() { try{ $this->ServiceObj = AnyClass::getService('XXX'); } catch{ return Redirect::to('/'); } } public function MyOwnFunction() { $getValueofCode = $this->_ServiceObj->set($endPoint_Url);...

jQuery animate does not work while everything else does

jquery,jquery-animate,try-catch
Could anyone could give me a clue on what I can do to debug jQuery in general and/or this issue in particular? Problem : jQuery method animate() behaves strangely. The method is added to the onclick method of a HTML element, javascript generated. This : try{ $(element).animate({ width : '300px'...

While and try-catch stracture and exceptions

java,exception-handling,try-catch
I want to get an input from user continually but with some restrictions. Input must contain 1 integer, 1 string, 1 integer, 1 string. (i.e. "3+1-", "1a4k"). If the user give input in a wrong way, I will warn like "Bad input". int a = scanner.nextInt(); String b = scanner.next();...

CATCH statement not firing in SQL script

sql,transactions,try-catch
I was looking for a way to create a "wrapper" around some SQL Script Statements that would be both Transactional (Commit / Rollback) and give some kind of error message to the screen for the user running the script. From another question, I posted I found what looked to be...

How to solve try / catch to load application on iPhone

ios,web-services,delphi,try-catch
I'm working with Delphi XE7 to develop an application for IOS. In the OnCreate of my application make a Caller Line the following method: url := 'http:// + Configuracao.getEnderecoServidor'; if not(Configuracao.getPortaServidor = '0') then begin url := url + ':' + Configuracao.getPortaServidor; end; url := url + '/WebServiceCGI/SgaWsCGI.exe/wsdl/ISgaWsCGI'; IdHTTP2.Head(url); code...

In Swift 2, how can I return JSON parsing errors to the completion block?

try-catch,swift2
I would like to create a function in Swift 2 that gets data from a URL and returns it as a JSON object using NSURLSession. At first, this seemed pretty straight forward. I wrote the following: func getJson(url:NSURL, completeWith: (AnyObject?,NSURLResponse?,NSError?)->Void) -> NSURLSessionTask? { let session = NSURLSession.sharedSession() let task =...

Can't catch certain exceptions

try-catch,abap
I am calling the cl_abap_typedescr=>describe_by_name method. It could possibly throw a TYPE_NOT_FOUND exception. I am coming form c# and in c# it would be quite easy to catch such an error. But in ABAP i am not able to catch the exception. It starts with the fact that I can't...

Does every exception have an required try-catch?

java,exception,try-catch,questionmark
A simple question and I can't find the answer for it. Is it required to every exception in Java to use a try-catch? Or is it only for the FileNotFoundException? A lot of exceptions (IndexOutOfBoundException, ArithmeticException, IlligalArgumentException, NullPointerException) are saying that they didn't need an Exception, but FileNotFoundException does)... and...

How can I execute all methods if I get exception in the first method?

c#,exception,c#-4.0,try-catch
I have 2 methods: method1() and method2(). Each method can create exception (WebException). I have methodMain() in this method I execute the first method is method1() and them I execute method2(). For example: public void methodMain() { ... try { method1(); method2(); } catch (WebException e) { //do something }...

Try block not catching - Am I making inadvertent internet access?

python,try-catch,praw
I accidentally disconnected my internet connection and received this error below. However, why did this line trigger the error? self.content += tuple(subreddit_posts) Or perhaps I should ask, why did the following line not lead to a sys.exit? It seems it should catch all errors: try: subreddit_posts = self.r.get_content(url, limit=10) except:...

How to fix this basic program? Java do-while loop

java,loops,try-catch,joptionpane,do-while
I am writing this guessing game, which enables the user to enter a number as the maximum number. The random generator will then pick a number between 1 and the max number entered by the user. It will save and display the number of high guesses and low guesses. The...

Exception Handling in a while loop

java,exception-handling,while-loop,try-catch,inputmismatchexception
The problem I am having with this code is the following: the variable number can't be a String so I tried to use a try, catch (InputMissmatchException) statement to take care of the issue. However, when in goes in the loop and someone enters a String, the exception is handle...

Using try-catch blocks for various exceptions (java)

java,try-catch
So I am trying to make a couple try-catch statements in my Postfix expression evaluator to catch exceptions that will come up from a input file. I just need help making those try-catch statements. So the current output is: 5 2 1 8 -4 2 -4 Exception in thread "main"...

Why does this code catch block not execute?

c++,multithreading,error-handling,try-catch
The catch handler is not run. But why? If the thread t is started before the try block, the catch handler runs. If the catch block's type does not match the type thrown, the program exits explaining that the thread terminated with an uncaught exception, suggesting that the exception is...

real-time TCL exec output

tcl,try-catch,exec
I have the following scenario: if { [catch { exec echo calling a BIG script } exec_msg] } { puts "NOK" puts "output of the BIG script: $exec_msg" } else { puts "OK" puts "output of the BIG script: $exec_msg" } Are there any solutions to print the $exec_msg in...

Safari not catching exception when trying to access parent window object with Javascript try/catch

javascript,osx,exception,safari,try-catch
So the code below can be seen working via the fiddle link. Safari is refusing to catch the exception- I am assuming this may be because it is not a 'Javascript' error? Either way, if you run the code in any other browser, you will see the page URL in...

Is there a need to catch exceptions that I've speciffied in throws clause?

java,exception,try-catch,throws
Is there a need to catch exceptions that I've specified in throws clause? And viceversa, is there a need to specify exceptions catched? public method() throws IOException, SQLException { ... try { .... }catch(IOException | SQLException ex) { ex.getMessage(); } } ...

Java throws out an exception where I think it shouldnt

java,exception,crash,try-catch
System.out.println("\nHow many sticks do you want?"); while(sticks==0){ try{ sticks=startInput.nextInt(); }catch(InputMismatchException e){ sticks=0; System.out.println("Please enter a valid number."); } sticks=startInput.nextInt(); } What I try to do: It asks for an int but when someone types in chars it should ask again instead of crashing....

Specifying throws IOException

java,exception,try-catch,throws
Can anyone help me solve my problem. I am a beginner in Java programming. Previously when I did not declare throws IOException it gave me an error: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.IOException; must be caught or declared to be thrown The program is...

Returning an error message to an end user upon exception in WebApi methods

c#,angularjs,asp.net-web-api,try-catch
I am currently building a WebApi service that connects with the backoffice of my application allowing the user to click a button an trigger a series of web service requests that trigger my Umbraco website to updated with content. The class for my WebApi service is setup as so: public...

Die reliably in response to a signal

perl,try-catch,signals
The following code is supposed to time out after a certain period, due to arrival of SIGALRM - sub sig_alrm_handler() { die "Timed out, sorry" } $SIG{ALRM} = \&sig_alrm_handler; main(); Usually this approach works, except sometimes main() includes a Try::Tiny 'try' block which intercepts the "die" from sig_alrm_handler, effectively ignoring...

Catch error and restart the if statement

powershell,error-handling,try-catch,catch-block
I have a powershell script that adds a computer to a domain. Sometimes, when I run the script I get the following error and when I run it for the second time it works. How can I make the script to check if I get this error, and if so...

Why is this forloop skipping items in the list?

python,for-loop,try-catch
When I run the code below it seems to only iterate through half of the total list of workers in the list. It then jumps to closing the parent process. I'm super confused why the code below isn't iterating through all the items in the list perhaps I've stared at...

Scala try-catch not catching exception

scala,try-catch
As far as I understand, the following code snippet should execute fine. Stream("A", "").toIterable.map(_.head) throws an exception, which should be caught by the try block. import org.scalatest.FunSuite class TryCatchTest extends FunSuite { test("Try failure") { List(1).flatMap { _ => try { Stream("A", "").toIterable.map(_.head) } catch { case e: Throwable =>...

throws Exception correct structure?

android,exception,try-catch
Just wondering if this is a correct structure to use with try and exceptions: MediaPlayer.OnCompletionListener videoViewCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) throws IllegalStateException { try { mp.stop(); mp.release(); videoView.stopPlayback(); } finally { toastDisplay.cancel(); toastDisplay = Toast.makeText(MainActivity.this, "Completed Video", Toast.LENGTH_LONG); toastDisplay.show(); } } }; Will it crash...

Why is @try not working

ios,objective-c,try-catch
I have a sensitive method that is doing operations with numbers and arrays. At one point I have something like this: @try { CGFloat value = [myArray[index] floatValue]; ... @catch (NSException *exception) { [self doSomething]; } @finally { } If index is a negative value or a value out of...

ERROR_PROCEDURE() returning NULL for code executed by SP_EXECUTESQL

sql-server,stored-procedures,try-catch
I have Stored procedure with a TRY CATCH statement and within that TRY CATCH I am calling another stored procedure which is throwing an error. An exception is thrown and caught however if the error is within the called stored procedure this is not shown in the ERROR_PROCEDURE() it is...

Shorter try except block for many vars

python,syntax,try-catch
I am parsing some content out of different urls. Not all the urls have the same structure and thus the code fails for some urls, so the code I came up with is this (simplified version): meta_dict = {} try: meta_dict['date_published'] = html.find('date'}).text except: meta_dict['date_published'] = '' try: meta_dict['headline'] =...

Try-Catch not working in TestComplete

javascript,try-catch,testcomplete
In test complete I am trying to use a try-catch block to see if a message box has an okay button and then click the okay button without crashing. I put the click operation inside a try block so if it fails the catch block can deal with the error,...

if condition in try process

android,if-statement,try-catch
i have some problem when trying to implement condition in "try" process, the result always of "globalnidn" always isi , therefore i've checked in logcat and the result is fine. :( protected void onPostExecute(String data) { try { JSONObject jObject = new JSONObject(data); globalnidn = null; globalnidn = jObject.getString("nidn"); String...

Can I try multiple things without nesting the try statements?

java,exception-handling,try-catch
My program is handling some JSON data. I want the program to be really stable over time and the JSON data can change as their source is being updated and improved. This is current function to return some image file name from the data: @Override public String createImgName() { try...

Why the need for closing a file within 'finally' and still have it embedded within a 'try/catch' block?

java,try-catch
The following code snippet ... try { myFile = new FileInputStream( "something.dat" ); ... } catch ( IOExcpetion ioe ) { ... } finally { try { myFile.close(); } catch ( Exception e ) { ... } } ... is closing the file within finally, which I understand. But why...

Python - peewee - Debugging statements - where are the errors logged

python,mysql,try-catch,peewee
I have just started to use peewee in python. But as i am saving table data using .save() function. There is an error in the line. and control does not go to the next line. Just wanted to know how can know what the error is. Although i have narrowed...

scala spark word2vec try and catch exception

scala,apache-spark,try-catch
I am trying to create a dictionary using spark's word2vec. In the process, I create an Array of around 200 words, and apply the findSynonyms function to each of them. However, out of the 200 words, there will be a few words that will not return any Synonyms (due to...

How to identify column throwing System.Data.SqlClient.SqlException? (conversion of a datetime2 data type to a datetime data type)

asp.net-mvc,entity-framework,try-catch
I have overridden my ApplicationDbContext.SaveChanges() method. This helps me by providing immediately visible error messages on the yellow and white error application error screen. But when there is a validation error with a DateTime column, the catch clause doesn't seem to be activated. Why is that? And how might I...

Avoid tryCatch to return something in case of fail

r,error-handling,try-catch
in a tryCatch function, I would like to don't return NULL or anything when the tryCatch fail. When you assign to an object an expression which returns an error if the object already exists his value isnt changed, e.g : > x <- 1 > x [1] 1 > x...

What kind of brackets should I use in try statements in Java?

java,try-catch
I have been reading in the Oracle Java Documentation a bit and noticed that they use '(' brackets in their try-Statements, but pretty much everyone else only uses '{'. Are there different cases where one should be preferred over the other or is there no difference between them? I couldn't...

How to get a try/catch error in Javascript when file doesn't exist?

javascript,css,file,try-catch
I replace a background image using Javascript in an element by calling a local file (not a URL). I want to try to catch an error if this file does not exist. So I tried the following code: try { thing.style.backgroundImage = str; } catch (err) { console.log(err.message); thing.style.backgroundImage =...

How to handle FileNotFoundError when “try .. except IOError” does not catch it?

python,exception,python-3.x,try-catch
How can I catch an error on python 3? I've googled a lot but none of the answers seem to be working. The file open.txt doesn't exist so it should print e.errno. This is what I tried now: This is in my defined function try: with open(file, 'r') as file:...

How do I get this simple Try/Catch test to work?

javascript,radio-button,try-catch
A user selects whether or not to run an alert line of code with an error using a radio button. The idea is the user selects a radio element, a function(setError()) is run that locates the selected radio button and then passes the value to another function (runCode()) that uses...