Search Results

Search found 36003 results on 1441 pages for 'try catch'.

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

  • 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

  • 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

  • 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

  • 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

  • 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

  • New/strange Java "try()" syntax?

    - by Ali
    While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I say code as follows: /** * 'try-with-resources' */ class Example { void foo() { try (FileReader reader1 = new FileReader("file1"); FileReader reader2 = new FileReader("file2")) { } } } I've never seen try used like this and I've been coding in Java for 9 years! Does any one know why you would do this? What is a possible use-case / benefit of doing this? An other pieces of code I saw, I thought was a very useful shorthand so I'm sharing it here as well, it's pretty obvious what it does: /** * 'multi-catch' */ class Example { void foo() { try { } catch (IllegalArgumentException | NullPointerException | ClassCastException e) { e.printStackTrace(); } } }

    Read the article

  • Enclosing service execution in try-catch: bad practice?

    - by Sorin Comanescu
    Hi, Below is the usual Program.cs content for a windows service program: static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); } } Is it a bad practice to enclose the ServiceBase.Run(...) in a try-catch block? Thanks.

    Read the article

  • Thoughts on try-catch blocks

    - by John Boker
    What are your thoughts on code that looks like this: public void doSomething() { try { // actual code goes here } catch (Exception ex) { throw; } } The problem I see is the actual error is not handled, just throwing the exception in a different place. I find it more difficult to debug because i don't get a line number where the actual problem is. So my question is why would this be good? ---- EDIT ---- From the answers it looks like most people are saying it's pointless to do this with no custom or specific exceptions being caught. That's what i wanted comments on, when no specific exception is being caught. I can see the point of actually doing something with a caught exception, just not the way this code is.

    Read the article

  • Enclosing service execution in try-catch

    - by Sorin Comanescu
    Hi, Below is the usual Program.cs content for a windows service program: static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); } } Is it a bad practice to enclose the ServiceBase.Run(...) in a try-catch block? Thanks.

    Read the article

  • Catching an exception that is nested into another exception

    - by Bernhard V
    Hi, I want to catch an exception, that is nested into another exception. I'm doing it currently this way: } catch (RemoteAccessException e) { if (e != null && e.getCause() != null && e.getCause().getCause() != null) { MyException etrp = (MyException) e.getCause().getCause(); ... } else { throw new IllegalStateException("Error at calling service 'beitragskontonrVerwalten'"); } } Is there a way to do this more efficient and elegant?

    Read the article

  • Catch test case order [on hold]

    - by DeadMG
    Can I guarantee the order of execution with multiple TEST_CASEs with Catch? I am testing some code using LLVM, and they have some despicable global state that I need to explicitly initialize. Right now I have one test case that's like this: TEST_CASE("", "") { // Initialize really shitty LLVM global variables. llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeNativeTarget(); llvm::InitializeAllAsmParsers(); // Some per-test setup I can make into its own function CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile(...)); CHECK_NOTHROW(Compile...)); CHECK_NOTHROW(Interpret(...)); CHECK_THROWS(Compile(...)); CHECK_THROWS(Compile(...)); } What I want is to refactor it into three TEST_CASE, one for tests that should pass compilation, one for tests that should fail, and -one for tests that should pass interpretation (and in the future, further such divisions, perhaps). But I can't simply move the test contents into another TEST_CASE because if that TEST_CASE is called before the one that sets up the inconvenient globals, then they won't be initialized and the testing will spuriously fail.

    Read the article

  • Try/Catch or test parameters

    - by Ondra Morský
    I was recently on a job interview and I was given a task to write simple method in C# to calculate when the trains meet. The code was simple mathematical equation. What I did was that I checked all the parameters on the beginning of the method to make sure, that the code will not fail. My question is: Is it better to check the parameters, or use try/catch? Here are my thoughts: Try/catch is shorter Try/catch will work always even if you forget about some condition Catch is slow in .NET Testing parameters is probably cleaner code (Exceptions should be exceptional) Testing parameters gives you more control over return values I would prefer testing parameters in methods longer than +/- 10 lines, but what do you think about using try/catch in simple methods just like this – i.e. return (a*b)/(c+d); There are many similar questions on stackexchnage, but I am interested in this particular scenario.

    Read the article

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