Search Results

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

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

  • error catching exception while System.out.print

    - by user1702633
    I have 2 classes, one that implements a double lookup( int i); and one where I use that lookup(int i) in solving a question, or in this case printing the lookup values. This case is for an array. So I read the exception documentation or google/textbook and come with the following code: public double lookup(int i) throws Exception { if( i > numItems) throw new Exception("out of bounds"); return items[i]; } and take it over to my class and try to print my set, where set is a name of the object type I define in the class above. public void print() { for (int i = 0; i < set.size() - 1; i++) { System.out.print(set.lookup(i) + ","); } System.out.print(set.lookup(set.size())); } I'm using two print()'s to avoid the last "," in the print, but am getting an unhandled exception Exception (my exception's name was Exception) I think I have to catch my exception in my print() but cannot find the correct formatting online. Do I have to write catch exception Exception? because that gives me a syntax error saying invalid type on catch. Sources like http://docs.oracle.com/javase/tutorial/essential/exceptions/ are of little help to me, I'm can't seem to grasp what the text is telling me. I'm also having trouble finding sources with multiple examples where I can actually understand the coding in the examples. so could anybody give me a source/example for the above catch phrase and perhaps a decent source of examples for new Java programmers? my book is horrendous and I cannot seem to find an understandable example for the above catch phrase online.

    Read the article

  • running code if try statements were successful in python

    - by None
    I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this: successful = False try: #code that might fail successful = True except: #error handling if code failed if successful: #code to run if try was successful that isn't part of try but I was wondering if there was a shorter way .

    Read the article

  • try .. catch blocks - when to use

    - 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

  • Catch not working and how to unset the exception handler

    - by neoneye
    catch is not working because there is installed an exception handler using set_exception_handler() I need "catch" to work, so I guess I need to unset the exception handler somehow. Things such as set_exception_handler(NULL) isn't working. Any ideas how to unset the exception handler? function my_exception_handler($exception) { error_log("caught exception: " . $exception->getMessage() ); } set_exception_handler("my_exception_handler"); // QUESTION: how does on unset it ? //set_exception_handler(NULL); try { throw new Exception('hello world'); error_log("should not happen"); } catch(Exception $e) { error_log("should happen: " . $e->getMessage()); } Actual output: caught exception: hello world Desired output: should happen: hello world

    Read the article

  • SQL Try catch purpose unclear

    - by PaN1C_Showt1Me
    Let's suppose I want to inform the application about what happened / returned the SQL server. Let's have this code block: BEGIN TRY -- Generate divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() as ErrorState, ERROR_PROCEDURE() as ErrorProcedure, ERROR_LINE() as ErrorLine, ERROR_MESSAGE() as ErrorMessage; END CATCH; GO and Let's have this code block: SELECT 1/0; My question is: Both return the division by zero error. What I don't understand clearly is that why I should surround it with the try catch clausule when I got that error in both cases ? Isn't it true that this error will be in both cases propagated to the client application ?

    Read the article

  • Refactor instance declaration from try block to above try block in a method

    - by dotnetdev
    Hi, Often I find myself coming across code like this: try { StreamWriter strw = new StreamWriter(); } However, there is no reference to the object outside the scope of the try block. How could I refactor (extract to field in Visual Studio says there is no field or something) the statement in the try block so that it is declared above the try block so I can use it anywhere in the method? Thanks

    Read the article

  • TRY/CATCH_ALL vs try/catch

    - by Tim
    I've been using c++ for a while, and I'm familiar with normal try/catch. However, I now find myself on Windows, coding in VisualStudio for COM development. Several parts of the code use things like: TRY { ... do stuff } CATCH_ALL(e) { ... issue a warning } END_CATCH_ALL; What's the point of these macros? What benefit do they offer over the built-in try/catch? I've tried googling this, but "try vs TRY" is hard to search for.

    Read the article

  • Actionscript 3.0 - drag and throw with easing

    - by Joe Hamilton
    I'm creating a map in flash and I would like to have a smooth movement similar to this: http://www.conceptm.nl/ I have made a start but I'm having trouble taking it to the next stage. My code currently throws the movieclip after the mouse is release but there is no easing while the mouse button is down. Any tips on how I would achieve this? Here is my current code: // Vars var previousPostionX:Number; var previousPostionY:Number; var throwSpeedX:Number; var throwSpeedY:Number; var isItDown:Boolean; // Event Listeners addEventListener(MouseEvent.MOUSE_DOWN, clicked); addEventListener(MouseEvent.MOUSE_UP, released); // Event Handlers function clicked(theEvent:Event) { isItDown =true; addEventListener(Event.ENTER_FRAME, updateView); } function released(theEvent:Event) { isItDown =false; } function updateView(theEvent:Event) { if (isItDown==true){ throwSpeedX = mouseX - previousPostionX; throwSpeedY = mouseY - previousPostionY; mcTestMovieClip.x = mouseX; mcTestMovieClip.y = mouseY; } else{ mcTestMovieClip.x += throwSpeedX; mcTestMovieClip.y += throwSpeedY; throwSpeedX *=0.9; throwSpeedY *=0.9; } previousPostionX= mcTestMovieClip.x; previousPostionY= mcTestMovieClip.y; }

    Read the article

  • Weird bug in Java try-catch-finally

    - by kcr
    I'm using JODConverter to convert .xls and .ppt to .pdf format. For this i have code something like try{ //do something System.out.println("connecting to open office"); OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100); System.out.println("connection object created"); connection.connect(); System.out.println("connection to open office successful"); //do something if(!successful) throw new FileNotFoundException(); }catch(Exception e){ System.out.println("hello here"); System.out.println("Caught Exception while converting to PDF "); LOGGER.error("Error in converting media" + e.getMessage()); throw new MediaConversionFailedException(); }finally{ decode_pdf.closePdfFile(); System.out.println("coming in finally"); //do something here } My Output : connecting to open office connection object created coming in finally P.S. return type of method is void How is it possible ? Even if there is some problem in connection.connect(), it s'd come in catch block. confused

    Read the article

  • ASP.NET/JavaScript: How to surround an auto generated JavaScript block with try/catch statement

    - by Rami Shareef
    In the Script documents that asp.net automatically generates how can I surround the whole generated scripts with try/catch statement to avoid 'Microsoft JScript Compilation error' My issue is: i got a DevExpress control (ASPxGridView) that added and set-up in run time, since i activated the grouping functionality in the grid I still get JS error says ';' expected whenever i use (click) on one of grouping/sorting abilities, I activated script Debugging for IE, in the JS code turns out that there is no missing ';' and once i click ignore for the error msg that VS generates every thing works fine, and surly end-user can't see this msg so i figured out if i try/catch the script that may help avoid this error. Thanks in advance

    Read the article

  • try catch finally

    - by gligom
    Maby this is simple for you, but for me is not. I have this code: Private int InsertData() { int rezultat = 0; try { if (sqlconn.State != ConnectionState.Open) { sqlconn.Open(); } rezultat = (int)cmd.ExecuteScalar(); } catch (Exception ex) { lblMesaje.Text = "Eroare: " + ex.Message.ToString(); } finally { if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); } } return rezultat; } Is just for inserting a new record in a table. Even if this throw an error "Specified cast is not valid." "rezultat=(int)cmd.ExecuteScalar();" - the code is executed and the row is inserted in the database, and the execution continues. Why it continues? Maby i don't understand the try catch finally yet Smile | :) Thank you!

    Read the article

  • Powershell: error handling with try and catch

    - by resolver101
    I'm writing a script and want to control the errors. However im having trouble finding information on error handling using the try, catch. I want to catch the specific error (shown below) and then perform some actions and resume the code. What code is needed for this? This is the code i am running and im entering in a invalid username when prompted. Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) Get-WmiObject : User credentials cannot be used for local connections At C:\Users\alex.kelly\AppData\Local\Temp\a3f819b4-4321-4743-acb5-0183dff88462.ps1:2 char:16 + Get-WMIObject <<<< Win32_Service -ComputerName localhost -Credential (Get-Credential) + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

    Read the article

  • Problem with "scopes" of variables in try catch blocks in Java

    - by devoured elysium
    Could anyone explain me why in the last lines, br is not recognized as variable? I've even tried putting br in the try clause, setting it as final, etc. Does this have anything to do with Java not support closures? I am 99% confident similar code would work in C#. private void loadCommands(String fileName) { try { final BufferedReader br = new BufferedReader(new FileReader(fileName)); while (br.ready()) { actionList.add(CommandFactory.GetCommandFromText(this, br.readLine())); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) br.close(); //<-- This gives error. It doesn't // know the br variable. } } Thanks

    Read the article

  • Can't declare unused exception variable when using catch-all pattern

    - by b0x0rz
    what is a best practice in cases such as this one: try { // do something } catch (SpecificException ex) { Response.Redirect("~/InformUserAboutAn/InternalException/"); } the warning i get is that ex is never used. however all i need here is to inform the user, so i don't have a need for it. do i just do: try { // do something } catch { Response.Redirect("~/InformUserAboutAn/InternalException/"); } somehow i don't like that, seems strange!!? any tips? best practices? what would be the way to handle this. thnx

    Read the article

  • How to free memory in try-catch blocks?

    - by Kra
    Hi, I have a simple question hopefully - how does one free memory which was allocated in the try block when the exception occurs? Consider the following code: try { char *heap = new char [50]; //let exception occur here delete[] heap; } catch (...) { cout << "Error, leaving function now"; //delete[] heap; doesn't work of course, heap is unknown to compiler return 1; } How can I free memory after the heap was allocated and exception occurred before calling delete[] heap? Is there a rule not to allocate memory on heap in these try .. catch blocks? Thanks

    Read the article

  • Have I to count transactions before rollback one in catch block in T-SQL?

    - by abatishchev
    I have next block in the end of each my stored procedure for SQL Server 2008 BEGIN TRY BEGIN TRAN -- my code COMMIT END TRY BEGIN CATCH IF (@@trancount > 0) BEGIN ROLLBACK DECLARE @message NVARCHAR(MAX) DECLARE @state INT SELECT @message = ERROR_MESSAGE(), @state = ERROR_STATE() RAISERROR (@message, 11, @state) END END CATCH Is it possible to switch CATCH-block to BEGIN CATCH ROLLBACK DECLARE @message NVARCHAR(MAX) DECLARE @state INT SELECT @message = ERROR_MESSAGE(), @state = ERROR_STATE() RAISERROR (@message, 11, @state) END CATCH or just BEGIN CATCH ROLLBACK END CATCH ?

    Read the article

  • Dont Throw Duplicate Exceptions

    In your code, youll sometimes have write code that validates input using a variety of checks.  Assuming you havent embraced AOP and done everything with attributes, its likely that your defensive coding is going to look something like this: public void Foo(SomeClass someArgument) { if(someArgument == null) { throw new InvalidArgumentException("someArgument"); } if(!someArgument.IsValid()) { throw new InvalidArgumentException("someArgument"); }   // Do Real Work } Do you see a problem here?  Heres the deal Exceptions should be meaningful.  They have value at a number of levels: In the code, throwing an exception lets the develop know that there is an unsupported condition here In calling code, different types of exceptions may be handled differently At runtime, logging of exceptions provides a valuable diagnostic tool Its this last reason I want to focus on.  If you find yourself literally throwing the exact exception in more than one location within a given method, stop.  The stack trace for such an exception is likely going to be identical regardless of which path of execution led to the exception being thrown.  When that happens, you or whomever is debugging the problem will have to guess which exception was thrown.  Guessing is a great way to introduce additional problems and/or greatly increase the amount of time require to properly diagnose and correct any bugs related to this behavior. Dont Guess Be Specific When throwing an exception from multiple code paths within the code, be specific.  Virtually ever exception allows a custom message use it and ensure each case is unique.  If the exception might be handled differently by the caller, than consider implementing a new custom exception type.  Also, dont automatically think that you can improve the code by collapsing the if-then logic into a single call with short-circuiting (e.g. if(x == null || !x.IsValid()) ) that will guarantee that you cant easily throw different information into the message as easily as constructing the exception separately in each case. The code above might be refactored like so:   public void Foo(SomeClass someArgument) { if(someArgument == null) { throw new ArgumentNullException("someArgument"); } if(!someArgument.IsValid()) { throw new InvalidArgumentException("someArgument"); }   // Do Real Work } In this case its taking advantage of the fact that there is already an ArgumentNullException in the framework, but if you didnt have an IsValid() method and were doing validation on your own, it might look like this: public void Foo(SomeClass someArgument) { if(someArgument.Quantity < 0) { throw new InvalidArgumentException("someArgument", "Quantity cannot be less than 0. Quantity: " + someArgument.Quantity); } if(someArgument.Quantity > 100) { throw new InvalidArgumentException("someArgument", "SomeArgument.Quantity cannot exceed 100. Quantity: " + someArgument.Quantity); }   // Do Real Work }   Note that in this last example, Im throwing the same exception type in each case, but with different Message values.  Im also making sure to include the value that resulted in the exception, as this can be extremely useful for debugging.  (How many times have you wished NullReferenceException would tell you the name of the variable it was trying to reference?) Dont add work to those who will follow after you to maintain your application (especially since its likely to be you).  Be specific with your exception messages follow DRY when throwing exceptions within a given method by throwing unique exceptions for each interesting case of invalid state. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Problem with continue in While Loop within Try/Catch in C# (2.0)

    - by csharpnoob
    Hi, when i try to use in my ASPX Webpage in the Code Behind this try{ while() { ... db.Open(); readDataMoney = new OleDbCommand("SELECT * FROM Customer WHERE card = '" + customer.card + "';", db).ExecuteReader(); while (readDataMoney.Read()) { try { if (!readDataMoney.IsDBNull(readDataMoney.GetOrdinal("Credit"))) { customer.credit = Convert.ToDouble(readDataMoney[readDataMoney.GetOrdinal("Credit")]); } if (!readDataMoney.IsDBNull(readDataMoney.GetOrdinal("Bonus"))) { customer.bonus = Convert.ToDouble(readDataMoney[readDataMoney.GetOrdinal("Bonus")]); } } catch (Exception ex) { Connector.writeLog("Money: " + ex.StackTrace + "" + ex.Message + "" + ex.Source); customer.credit = 0.0; customer.credit = 0.0; continue; } finally { } } readDataMoney.Close(); vsiDB.Close(); ... } }catch { continue; } The whole page hangs if there is a problem when the read from db isn't working. I tried to check for !isNull, but same problem. I have a lots of differend MDB Files to process, which are readonly (can't repair/compact) and some or others not. Same Design/Layout of Tables. With good old ASP Classic 3.0 all of them are processing with the "On Resume Next". I know I know. But that's how it is. Can't change the source. So the basic question: So is there any way to tell .NET to continue the loop whatever happens within the try loop if there is any exception? After a lots of wating time i get this exceptions: at System.Data.Common.UnsafeNativeMethods.IDBInitializeInitialize.Invoke(IntPtr pThis) at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper) at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at GetCustomer(String card)Thread was being aborted.System.Data and System.Runtime.InteropServices.Marshal.ReadInt16(IntPtr ptr, Int32 ofs) System.Data.ProviderBase.DbBuffer.ReadInt16(Int32 offset) System.Data.OleDb.ColumnBinding.Value_I2() System.Data.OleDb.ColumnBinding.Value() System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal) System.Data.OleDb.OleDbDataReader.get_Item(Int32 index) Thread was terminated.mscorlib Thanks for any help.

    Read the article

  • Asp.net MVC Route class that supports catch-all parameter anywhere in the URL

    - by Robert Koritnik
    the more I think about it the more I believe it's possible to write a custom route that would consume these URL definitions: {var1}/{var2}/{var3} Const/{var1}/{var2} Const1/{var1}/Const2/{var2} {var1}/{var2}/Const as well as having at most one greedy parameter on any position within any of the upper URLs like {*var1}/{var2}/{var3} {var1}/{*var2}/{var3} {var1}/{var2}/{*var3} There is one important constraint. Routes with greedy segment can't have any optional parts. All of them are mandatory. Example This is an exemplary request http://localhost/Show/Topic/SubTopic/SubSubTopic/123/This-is-an-example This is URL route definition {action}/{*topicTree}/{id}/{title} Algorithm Parsing request route inside GetRouteData() should work like this: Split request into segments: Show Topic SubTopic SubSubTopic 123 This-is-an-example Process route URL definition starting from the left and assigning single segment values to parameters (or matching request segment values to static route constant segments). When route segment is defined as greedy, reverse parsing and go to the last segment. Parse route segments one by one backwards (assigning them request values) until you get to the greedy catch-all one again. When you reach the greedy one again, join all remaining request segments (in original order) and assign them to the greedy catch-all route parameter. Questions As far as I can think of this, it could work. But I would like to know: Has anyone already written this so I don't have to (because there are other aspects to parsing as well that I didn't mention (constraints, defaults etc.) Do you see any flaws in this algorithm, because I'm going to have to write it myself if noone has done it so far. I haven't thought about GetVirtuaPath() method at all.

    Read the article

  • javascript - catch SyntaxError and run alternate function

    - by ludicco
    Hello there, I'm trying to build something on javascript that I can have an input that can be everything like string, xml, javascript and (non-javascript string without quotes) as follows: //strings eval("'hello I am a string'"); /* note the following proper quote marks */ //xml eval(<p>Hello I am a XML doc</p>); //javascript eval("var hello = 2+2;"); So this first 3 are working well since they are simple javascript native formats but when I try use this inside javascript //plain-text without quotes eval("hello I am a plain text without quotes"); //--SyntaxError: missing ; before statement:--// Obviously javascript interprets this as syntax error because it thinks its javascript throwing a SyntaxError. So what I would like to do it to catch this error and perform the adjustment method if this occurs. I've already tried with try catch but it doesn't work since it keeps returning the Syntax error as soon as it tries to execute the code. Any help would be much appreciated Cheers :) Additional Information: Imagine an external file that javascript would read, using spidermonkey, so it's a non-browser stuff(I can't use HttpRequest, DOM, etc...)..not sure if this matters, but there it is. :)

    Read the article

  • How to catch segmentation fault in Linux?

    - by Alex Farber
    I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I could do this with __try - __catch. Is there cross-platform or platform-specific way to do the same? I need this in Linux, gcc.

    Read the article

  • Best way to implement try catch in php4

    - by rgz
    What is the closest you can get to a try-catch block in php4? I'm in the middle of a callback during an xmlrpc request and it's required to return a specifically structured array no matter what. I have to error check all accesses to external resources, resulting in a deep stack of nested if-else blocks, ugly.

    Read the article

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