Search Results

Search found 38690 results on 1548 pages for 'try catch throw'.

Page 4/1548 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Should try...catch go inside or outside a loop?

    - by mmyers
    I have a loop that looks something like this: for(int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return null if there is an error, so I put the loop inside a try...catch block, like this: try { for(int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } } catch (NumberFormatException ex) { return null; } But then I also thought of putting the try...catch block inside the loop, like this: for(int i = 0; i < max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum; } So my question is: is there any reason, performance or otherwise, to prefer one over the other? EDIT: The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer? (EDIT: did it myself, but voted up Jeffrey and Ray's answers)

    Read the article

  • Check If You Are Eligible To Try Amazon Fire TV Free for 30 days

    - by Gopinath
    Re/Code first broke the story of Amazon offering its customers to try Amazon Fire TV free for 30 days. The Amazon Fire TV costs $99 but with this offer you get a chance to try it for 30 days without paying any money. After 30 days if you are interested you can keep it with you by paying $99 otherwise you can return it to Amazon. All the costs associated with shipping to your home as well as returning back to Amazon are covered by the offer, which means it’s a real FREE offer to try! This offer is not available for everyone, but selected customers are receiving emails from Amazon. If you are interested to try free Amazon TV either you may wait to receive an offer email or click on this link to check if you are eligible. I verified it today and it says that I’m not eligible for this offer. Try your luck and all the best.

    Read the article

  • Arguments for or against using Try/Catch as logical operators

    - by James P. Wright
    I just discovered some lovely code in our companies app that uses Try-Catch blocks as logical operators. Meaning, "do some code, if that throws this error, do this code, but if that throws this error do this 3rd thing instead". It uses "Finally" as the "else" statement it appears. I know that this is wrong inherently, but before I go picking a fight I was hoping for some well thought out arguments. And hey, if you have arguments FOR the use of Try-Catch in this manner, please do tell. EDIT For any who are wondering, the language is C# and the code in question is about 30+ lines and is looking for specific exceptions, it is not handling ALL exceptions.

    Read the article

  • It&rsquo;s ok to throw System.Exception&hellip;

    - by Chris Skardon
    No. No it’s not. It’s not just me saying that, it’s the Microsoft guidelines: http://msdn.microsoft.com/en-us/library/ms229007.aspx  Do not throw System.Exception or System.SystemException. Also – as important: Do not catch System.Exception or System.SystemException in framework code, unless you intend to re-throw.. Throwing: Always, always try to pick the most specific exception type you can, if the parameter you have received in your method is null, throw an ArgumentNullException, value received greater than expected? ArgumentOutOfRangeException. For example: public void ArgChecker(int theInt, string theString) { if (theInt < 0) throw new ArgumentOutOfRangeException("theInt", theInt, "theInt needs to be greater than zero."); if (theString == null) throw new ArgumentNullException("theString"); if (theString.Length == 0) throw new ArgumentException("theString needs to have content.", "theString"); } Why do we want to do this? It’s a lot of extra code when compared with a simple: public void ArgChecker(int theInt, string theString) { if (theInt < 0 || string.IsNullOrWhiteSpace(theString)) throw new Exception("The parameters were invalid."); } It all comes down to a couple of things; the catching of the exceptions, and the information you are passing back to the calling code. Catching: Ok, so let’s go with introduction level Exception handling, taught by many-a-university: You do all your work in a try clause, and catch anything wrong in the catch clause. So this tends to give us code like this: try { /* All the shizzle */ } catch { /* Deal with errors */ } But of course, we can improve on that by catching the exception so we can report on it: try { } catch(Exception ex) { /* Log that 'ex' occurred? */ } Now we’re at the point where people tend to go: Brilliant, I’ve got exception handling nailed, what next??? and code gets littered with the catch(Exception ex) nastiness. Why is it nasty? Let’s imagine for a moment our code is throwing an ArgumentNullException which we’re catching in the catch block and logging. Ok, the log entry has been made, so we can debug the code right? We’ve got all the info… What about an OutOfMemoryException – what can we do with that? That’s right, not a lot, chances are you can’t even log it (you are out of memory after all), but you’ve caught it – and as such - have hidden it. So, as part of this, there are two things you can do one, is the rethrow method: try { /* code */ } catch (Exception ex) { //Log throw; } Note, it’s not catch (Exception ex) { throw ex; } as that will wipe all your important stack trace information. This does get your exception to continue, and is the only reason you would catch Exception (anywhere other than a global catch-all) in your code. The other preferred method is to catch the exceptions you can deal with. It may not matter that the string I’m passing in is null, and I can cope with it like this: try{ DoSomething(myString); } catch(ArgumentNullException){} And that’s fine, it means that any exceptions I can’t deal with (OutOfMemory for example) will be propagated out to other code that can deal with it. Of course, this is horribly messy, no one wants try / catch blocks everywhere and that’s why Microsoft added the ‘Try’ methods to the framework, and it’s a strategy we should continue. If I try: int i = (int) "one"; I will get an InvalidCastException which means I need the try / catch block, but I could mitigate this using the ‘TryParse’ method: int i; if(!Int32.TryParse("one", out i)) return; Similarly, in the ‘DoSomething’ example, it might be beneficial to have a ‘TryDoSomething’ that returns a boolean value indicating the success of continuing. Obviously this isn’t practical in every case, so use the ol’ common sense approach. Onwards Yer thanks Chris, I’m looking forward to writing tonnes of new code. Fear not, that is where helpers come into it… (but that’s the next post)

    Read the article

  • Why is this SocketException not caught by a generic catch routine?

    - by Tarnschaf
    Our company provides a network component (DLL) for a GUI application. It uses a Timer that checks for disconnections. If it wants to reconnect, it calls: internal void timClock_TimerCallback(object state) { lock (someLock) { // ... try { DoConnect(); } catch (Exception e) { // Log e.Message omitted // Raise event with e as parameter ErrorEvent(this, new ErrorEventArgs(e)); DoDisconnect(); } // ... } } So the problem is, inside of the DoConnect() routine a SocketException is thrown (and not caught). I would assume, that the catch (Exception e) should catch ALL exceptions but somehow the SocketException was not caught and shows up to the GUI application. protected void DoConnect() { // client = new TcpClient(); client.NoDelay = true; // In the following call the SocketException is thrown client.Connect(endPoint.Address.ToString(), endPoint.Port); // ... (login stuff) } The doc confirmed that SocketException extends Exception. The stacktrace that showed up is: TcpClient.Connect() -> DoConnect() -> timClock_TimerCallback So the exception is not thrown outside the try/catch block. Any ideas why it doesn't work?

    Read the article

  • Why should I not wrap every block in "try"-"catch"?

    - by Konrad
    I have always been of the belief that if a method can throw an exception then it is reckless not to protect this call with a meaningful try block. I just posted 'You should ALWAYS wrap calls that can throw in try, catch blocks.' to this question and was told that it was 'remarkably bad advice' - I'd like to understand why. Thanks!

    Read the article

  • Unhandled exception, even after adding try-catch block ? C++

    - by user2525503
    try { bool numericname=false; std::cout <<"\n\nEnter the Name of Customer: "; std::getline(cin,Name); std::cout<<"\nEnter the Number of Customer: "; std::cin>>Number; std::string::iterator i=Name.begin(); while(i!=Name.end()) { if(isdigit(*i)) { numericname=true; } i++; } if(numericname) { throw "Name cannot be numeric."; } } catch(string message) { cout<<"\nError Found: "<< message <<"\n\n"; } Why am I getting unhandled exception error ? Even after I have added the catch block to catch thrown string messages?

    Read the article

  • How to configure catch-all in Exchange2010 hub-transport environment?

    - by Itay Levin
    Im getting the delivery failed from the post master reply. i don't want it. because then poeple can find out all my real users on the exchange. also, i have a lot of users (10K) in my application - and i don't want to create a mailbox for each user. is it possible to get this done in ex2010 sp1. hub-transport configuration? or i must use edge-transport as indicated in http://technet.microsoft.com/en-us/library/bb691132(EXCHG.80).aspx

    Read the article

  • Quadcopters Play Catch [Video]

    - by Jason Fitzpatrick
    Working like a group of hive-minded bees, these quadcopters come off as almost playful with their ball throwing antics. Courtesy of the folks at the Swiss Federal Institute of Technology in Zurich’s Institute for Dynamic Systems and Control, we’re treated to a video of three quadcopters playing catch in the research facility’s Flying Machine Area. They explain the processes demonstrated in the video: This video shows three quadrocopters cooperatively tossing and catching a ball with the aid of an elastic net. To toss the ball, the quadrocopters accelerate rapidly outward to stretch the net tight between them and launch the ball up. Notice in the video that the quadrocopters are then pulled forcefully inward by the tension in the elastic net, and must rapidly stabilize in order to avoid a collision. Once recovered, the quadrotors cooperatively position the net below the ball in order to catch it. Because they are coupled to each other by the net, the quadrocopters experience complex forces that push the vehicles to the limits of their dynamic capabilities. To exploit the full potential of the vehicles under these circumstances requires several novel algorithms, including: HTG Explains: How Antivirus Software Works HTG Explains: Why Deleted Files Can Be Recovered and How You Can Prevent It HTG Explains: What Are the Sys Rq, Scroll Lock, and Pause/Break Keys on My Keyboard?

    Read the article

  • why does Visual Studio not enforce try-catch-block implementation?

    - by Pedro
    Coming from Eclipse/Java, I noticed that in VisualStudio/C# it is not mandatory to care about Exceptions. While Eclipse forces the user to implement a try-catch-block or to add a throws declaration, this is not the case in Visual Studio. What is the reason Visual Studio doesn't inform about unhandled exceptions? Can I configure Visual Studio to force me to implement try-catch-blocks, or at least add a compiler-warning?

    Read the article

  • Throw Things at Me…In Person!

    - by Most Valuable Yak (Rob Volk)
    I have a few speaking engagements coming up in July.  I will be getting my Revenge on twice this week, first at the Steel City SQL User Group in Birmingham, Alabama July 17, 2012: New Horizon Computer Learning Center 601 Beacon Pkwy. West, Suite 106 Birmingham, AL 35209 Register: http://steelcitysqljul2012.eventbrite.com/ 6-8 pm CST Not content with that, with my hands behind my back, I will pull the same thing from my hat at SQL Saturday 122 in Louisville, KY on July 21, 2012: Schedule Register These include Revenge: The SQL Parts 1 AND 2!  New and improved with the new Office 2013 Preview!  (Ummm, not really). I will then Tame Unruly Data at SQL Saturday 126 in Indianapolis, IN in July 28, 2012: Schedule Register If you will be in any of those places at those times, and I owe you money, that would be the best time for you to collect.  Just make sure not to warn me first, otherwise I may not show.

    Read the article

  • Best way to throw exception and avoid code duplication

    - by JF Dion
    I am currently writing code and want to make sure all the params that get passed to a function/method are valid. Since I am writing in PHP I don't have access to all the facilities of other languages like C, C++ or Java to check for parameters values and types public function inscriptionExists($sectionId, $userId) // PHP vs. public boolean inscriptionExists(int sectionId, int userId) // Java So I have to rely on exceptions if I want to make sure that my params are both integers. Since I have a lot of places where I need to check for param validity, what would be the best way to create a validation/exception machine and avoid code duplication? I was thinking on a static factory (since I don't want to pass it to all of my classes) with a signature like: public static function factory ($value, $valueType, $exceptionType = 'InvalidArgumentException'); Which would then call the right sub process to validate based on the type. Am I on the right way, or am I going completely off the road and overthinking my problem?

    Read the article

  • Parabolic throw with set Height and range (libgdx)

    - by Tauboga
    Currently i'm working on a minigame for android where you have a rotating ball in the center of the display which jumps when touched in the direction of his current angle. I'm simply using a gravity vector and a velocity vector in this way: positionBall = positionBall.add(velocity); velocity = velocity.add(gravity); and velocity.x = (float) Math.cos(angle) * 12; /* 12 to amplify the velocity */ velocity.y = (float) Math.sin(angle) * 15; /* 15 to amplify the velocity */ That works fine. Here comes the problem: I want to make the jump look the same on all possible resolutions. The velocity needs to be scaled in a way that when the ball is thrown straight upwards it will touch the upper display border. When thrown directly left or right the range shall be exactly long enough to touch the left/right display border. Which formula(s) do I need to use and how to implement them correctly? Thanks in advance!

    Read the article

  • All chromium extensions throw errors since update to 13.10

    - by hugo der hungrige
    Since updating to 13.10 all chromium extensions generate errors: chrome.extension is not available: 'extension' is not allowed for specified context type content script, extension page, web page, etc.). [VM] binding (56):427 Uncaught TypeError: Cannot call method 'sendRequest' of undefined include.preload.js:105 Uncaught TypeError: Cannot read property 'onRequest' of undefined include.postload.js:473 GET http://edge.quantserve.com/quant.js superuser.com/:2047 GET http://www.google-analytics.com/__utm.gif?utmwv=5.4.5&utms=2&utmn=590704726…n%3D(organic)%7Cutmcmd%3Dorganic%7Cutmctr%3D(not%2520provided)%3B&utmu=qQ~ ga.js:61 chrome.extension is not available: 'extension' is not allowed for specified context type content script, extension page, web page, etc.). [VM] binding (56):427 Uncaught TypeError: Cannot read property 'onRequest' of undefined content.js:233 chrome.extension is not available: 'extension' is not allowed for specified context type content script, extension page, web page, etc.). [VM] binding (56):427 Uncaught TypeError: Cannot read property 'onRequest' of undefined injected.js:169 chrome.extension is not available: 'extension' is not allowed for specified context type content script, extension page, web page, etc.). [VM] binding (56):427 Uncaught TypeError: Cannot call method 'getURL' of undefined content_js_min.js:5 GET http://engine.adzerk.net/z/8476/adzerk2_2_17_47 superuser.com/:1719 Uncaught TypeError: Cannot call method 'sendRequest' of undefined How to fix this?

    Read the article

  • Chargeback and showback...both a 'throw back'

    - by llaszews
    Been getting asked again by customers and partners about chargeback and showback in the cloud so thought I would blog on my response to this question. Charge Back background, information and industry analysis: Cloud computing is all about shared resources. These shared resources are computer servers (including memory and CPU), network devices, hard disk storage, database servers, application servers, cooling, floor space, electricity and more. These resources are shared by departments within a company, or by a number of companies, when resources are hosted in the public or hybrid cloud. Currently, hosting providers that run other companies on their cloud platforms do not have an accurate way to measure the shared computing resources used by a specific user let alone used by a specific customer. Additionally, companies running their own cloud data centers, for private or hybrid clouds, have no way of measure and charging back the departments in the company that are using these shared cloud resources. In both cases, the lack of determine shared resource costs and to charge them back to the company, department or user that is using this resources is limited a clear measure of business benefit and impacting company’s ability to measure the Return on Investment (ROI). An IT chargeback system is an accounting strategy that applies the costs of IT services, hardware or software to the business unit in which they are used. This system contrasts with traditional IT accounting models in which a centralized department bears all of the IT costs in an organization and those costs are treated simply as corporate overhead. Showback involves showing the IT costs to a department or customer but not actually charging them for their IT usage. Showback is a gradual method of introducing chargeback into an enterprise. Most companies implement a show back mechanism before a full chargeback system is put in place. Oracle chargeback product: Oracle Enterprise Manager provides tools for defining detailed Chargeback plans spanning different metrics collected for each type of resources as well as defining Cost Centers for grouping costs across multiple developers. Chargeback plans can use not only usage based costs, but also configuration based costs (e.g. version of the platform) or fixed costs (e.g. flat-rate management fee). Chargeback has rich out of the box reports. Trending reports show how charge and resource consumption varies over time, while Summary reports show the breakdown of charges or usage by different dimensions such as Cost Center or Target Type. These reports help consumers in understanding how their charges relate to their consumption and also assist the IT department with budgeting and planning activities. With BI Publisher, the reports can be made available in a variety of formats such as PDF, HTML, Word, Excel or PowerPoint.

    Read the article

  • Save programmatically created Mesh to .X Files using SlimDX throw null exception

    - by zionpi
    Mesh has been created properly using SlimDX,but when I use the following line: Mesh.ToXFile(barMesh, "foo.x", XFileFormat.Text,CharSet.Unicode); It throws NullReferenceException,through monitor window I can see barMesh is not null, inside the mesh structrue, SkinInfo is null. If SkinInfo is the problem,then how can I initialize it properly?Internet doesn't seems have much information on this.

    Read the article

  • SEHException throw using Microsoft XACT Audio Framework (XACT3)

    - by Sweta Dwivedi
    I have been developing a game using Kinect + XNA and using Microsoft Audio Creation tool (XACT3) for managing my sound files and music, however in the code an SEHException is thrown whenever it tries to get the wave file from the wave Bank . . Sometimes the code works magically and all of a sudden it will start throwing this exception randomly ..I need a help on solving this exception /*Declaring Audio Engine for music*/ AudioEngine engine; SoundBank soundBank; WaveBank waveBank; Cue cue; /*Declaring Audio engine for sound effects*/ AudioEngine engine1; SoundBank soundbank; WaveBank wavebank; Cue effect; engine = new AudioEngine(@"Content\therapy.xgs"); soundBank = new SoundBank(engine, @"Content\Sound Bank.xsb"); **waveBank = new WaveBank(engine, @"Content\Wave Bank.xwb");** cue = null; engine1 = new AudioEngine(@"Content\Music_Manager\Sound_effects.xgs"); soundbank = new SoundBank(engine1, @"Content\Music_Manager\Sound1.xsb"); **wavebank = new WaveBank(engine1, @"Content\Music_Manager\Wave1.xwb");** effect = null; cue = soundBank.GetCue("hypnotizing"); cue.Play();

    Read the article

  • After update, audio won't play throw hdmi cable

    - by ckhenderson
    Yesterday (June 7th) I faithfully updated a bunch of stuff through update manager (though I'm not sure what since I never read what I updated any more because I'm a bad person). Afterward, I discovered that I could no longer play audio through my tv via HDMI. The sound settings menu seems to have completely changed and the shell script that I wrote a week ago (with much pain and effort as I had never before written a shell script) to toggle between my laptop speakers and the HDMI cable output no longer works. When I type in pactl set-card-profile 0 output:hdmi-surround in the command line I get Failure: No such entity Presumably this means something with Pulse Audio changed but, while I'm learning a lot about the inner workings of Ubuntu/Linux, I'm not an expert and would love some help. EDIT: So I noticed that pacmd set-card-profile 0 output:hdmi-stereo seems to get everything working. Still, shouldn't there be a way to do this through the GUI as well?

    Read the article

  • Finding the try for an except or finally [migrated]

    - by ?s?
    I'm dealing with some code that has fantastically long methods (10k lines!) and some odd use of try-finally and try-except blocks. Some of the latter are long by themselves, and don't always have the try at the start of the method. Obviously I'm trying to refactor the code, but in the meantime just being able to fix a couple of common pathologies would be much easier if I could jump to the start of a block and see what is happening there. When it's 20+ pages away finding it even with the CNPack rainbows is just tedious. I'm using D2010 and have GExperts (with DelForExp), CNPack and DDevExtensions installed, but I can't find anything that lets me jump from the try to the finally or back. Am I missing something? Is there another add-in that I can use that will get me this?

    Read the article

  • Can you catch exceeded allocated memory error before it kills the script?

    - by kristovaher
    The thing is that I want to catch memory problems before they happen. I have a system that gets rows from database and casts the returned associative array to a variable, but I never know what the size of the database result is is or how much memory it will take once the database request is made. This means that my software can fail simply because memory is exceeded. But I want to avoid that somehow. One of the ways is to obviously make database requests that are smaller, but what if this is not possible or what if I do not know the size of data that is returned from database? Is it possible to 'catch' situations where memory use is exceeded in PHP? Something like this: $requestOk=memory_test(function(){ return doSomething(); }); if($requestOk){ // Memory seems fine // $requestOk now has the value from memory_test() function } else { // Function would have exceeded memory } I just find it problematic that my script can just die at any moment because of memory issues. From what I know, try-catch cannot be used here because it is a fatal error. Any help would be appreciated!

    Read the article

  • How do I implement a fibonacci sequence in java using try/catch logic?

    - by Lars Flyger
    I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it. So far I have: public static int fibo(int index) { int sum = 0; try { fibo_aux(index, 1, 1); } catch (IntegerException me) { sum = me.getIntValue(); } return sum; } fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?

    Read the article

  • [Blog] N'utilisez jamais try {} catch {}

    C'est en somme le conseil donn? par Karl Seguin sur son blog. Pour lui, l'utilisation du try/catch pour g?rer une exception est une mauvaise pratique : "If an exception happens, you need to know about it. If a truly unexpected exception happens, you're better off (most of the time) crashing than letting the application continue (...) The best way to achieve both is let the exception go unhandled and log the exception in a global exception handler". Pour paraphraser une ?mission c?l?bre, ?a se discute ...

    Read the article

  • Spring can commit Transaction in finally block with RunTimeException in try block [migrated]

    - by Chance Lai
    The project used Spring + Hibernate Sample code: public void method(){ try{ dao.saveA(entityA); throw RuntimeException; dao.saveB(entityB); }catch(RuntimeException e){ throw e; }finally{ dao.saveC(entityC) } } Finally, just entityC will be saved in database in test. I think saveA, saveB, saveC in the same transaction,they should not be committed. In this case, I want to know why entityC is committed. How does Spring do this in the finally block?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >