Search Results

Search found 38423 results on 1537 pages for 'try finally'.

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

  • Difference between try-finally and try-catch

    - by Vijay Kotari
    What's the difference between try { fooBar(); } finally { barFoo(); } and try { fooBar(); } catch(Throwable throwable) { barFoo(throwable); // Does something with throwable, logs it, or handles it. } I like the second version better because it gives me access to the Throwable. Is there any logical difference or a preferred convention between the two variations? Also, is there a way to access the exception from the finally clause?

    Read the article

  • Java try finally variations

    - by Petr Gladkikh
    This question nags me for a while but I did not found complete answer to it yet (e.g. this one is for C# http://stackoverflow.com/questions/463029/initializing-disposable-resources-outside-or-inside-try-finally). Consider two following Java code fragments: Closeable in = new FileInputStream("data.txt"); try { doSomething(in); } finally { in.close(); } and second variation Closeable in = null; try { in = new FileInputStream("data.txt"); doSomething(in); } finally { if (null != in) in.close(); } The part that worries me is that the thread might be somewhat interrupted between the moment resource is acquired (e.g. file is opened) but resulting value is not assigned to respective local variable. Is there any other scenarios the thread might be interrupted in the point above other than: InterruptedException (e.g. via Thread#interrupt()) or OutOfMemoryError exception is thrown JVM exits (e.g. via kill, System.exit()) Hardware fail (or bug in JVM for complete list :) I have read that second approach is somewhat more "idiomatic" but IMO in the scenario above there's no difference and in all other scenarios they are equal. So the question: What are the differences between the two? Which should I prefer if I do concerned about freeing resources (especially in heavily multi-threading applications)? Why? I would appreciate if anyone points me to parts of Java/JVM specs that support the answers.

    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

  • Understanding try..catch in Javascript

    - by user295189
    I have this try and catch problem. I am trying to redirect to a different page. But sometimes it does and some times it doesnt. I think the problem is in try and catch . can someone help me understand this. Thanks var pg = new Object(); var da = document.all; var wo = window.opener; pg.changeHideReasonID = function(){ if(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0){ pg.otherReason.style.backgroundColor = "ffffff"; pg.otherReason.disabled = 0; pg.otherReason.focus(); } else { pg.otherReason.style.backgroundColor = "f5f5f5"; pg.otherReason.disabled = 1; } } pg.exit = function(pid){ try { if(window.opener.hideRecordReload){ window.opener.hideRecordReload(pg.recordID, pg.recordTypeID); } else { window.opener.pg.hideRecord(pg.recordID, pg.recordTypeID); } } catch(e) {} try { window.opener.pg.hideEncounter(pg.recordID); } catch(e) {} try { window.opener.pg.hideRecordResponse(pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text); } catch(e) {} try { window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID); } catch(e) {} try { window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID); } catch(e) {} try { window.opener.window.parent.frames[1].pg.loadQualityMeasureRequest(); } catch(e) {} try { window.opener.pg.closeWindow(); } catch(e) {} parent.loadCenter2({reportName:'redirectedpage',patientID:pid}); parent.$.fancybox.close(); } pg.hideRecord = function(){ var pid = this.pid; pg.otherReason.value = pg.otherReason.value.trim(); if(pg.hideReasonID.selectedIndex == 0){ alert("You have not indicated your reason for hiding this record."); pg.hideReasonID.focus(); } else if(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0 && pg.otherReason.value.length < 2){ alert("You have indicated that you wish to enter a reason\nnot on the list, but you have not entered a reason."); pg.otherReason.focus(); } else { pg.workin(1); var n = new Object(); n.noheaders = 1; n.recordID = pg.recordID; n.recordType = pg.recordType; n.recordTypeID = pg.recordTypeID; n.encounterID = request.encounterID; n.hideReasonID = pg.hideReasonID.value; n.hideReason = pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text; Connect.Ajax.Post("/emr/hideRecord/act_hideRecord.php", n, pg.exit(pid)); } } pg.init = function(){ pg.blocker = da.blocker; pg.hourglass = da.hourglass; pg.content = da.pageContent; pg.recordType = da.recordType.value; pg.recordID = parseInt(da.recordID.value); pg.recordTypeID = parseInt(da.recordTypeID.value); pg.information = da.information; pg.hideReasonID = da.hideReasonID; pg.hideReasonID.onchange = pg.changeHideReasonID; pg.hideReasonID.tabIndex = 1; pg.otherReason = da.otherReason; pg.otherReason.tabIndex = 2; pg.otherReason.onblur = function(){ this.value = this.value.trim(); } pg.otherReason.onfocus = function(){ this.select(); } pg.btnCancel = da.btnCancel; pg.btnCancel.tabIndex = 4; pg.btnCancel.title = "Close this window"; pg.btnCancel.onclick = function(){ //window.close(); parent.$.fancybox.close(); } pg.btnHide = da.btnHide; pg.btnHide.tabIndex = 3; pg.btnHide.onclick = pg.hideRecord; pg.btnHide.title = "Hide " + pg.recordType.toLowerCase() + " record"; document.body.onselectstart = function(){ if(event.srcElement.tagName.search(/INPUT|TEXT/i)){ return false; } } pg.workin(0); } pg.workin = function(){ var n = arguments.length ? arguments[0] : 1; pg.content.disabled = pg.hideReasonID.disabled = n; pg.blocker.style.display = pg.hourglass.style.display = n ? "block" : "none"; if(n){ pg.otherReason.disabled = 1; pg.otherReason.style.backgroundColor = "f5f5f5"; } else { pg.otherReason.disabled = !(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0); pg.otherReason.style.backgroundColor = pg.otherReason.disabled ? "f5f5f5" : "ffffff"; pg.hideReasonID.focus(); } }

    Read the article

  • Java: error handling with try-catch, empty-try-catch, dummy-return

    - by HH
    A searh uses recursively defined function that easily throws exceptions. I have tried 3 ways to handle exeptions: to ignore with an empty-try-catch() add-dummy-return stop err-propagation due to exeption throw a specific except. (this part I don't really understand. If I throw except, can I force it to continue elsewhere, not continuing the old except-thrown-path?) Some exceptions I do not realy care like during execution removed files -exception (NullPointer) but some I really do like unknown things. Possible exceptions: // 1. if a temp-file or some other file removed during execution -> except. // 2. if no permiss. -> except. // 3. ? --> except. The code is Very import for the whole program. I earlier added clittered-checks, try-catches, avoided-empty-try-catches but it really blurred the logic. Some stoned result here would make the code later much easier to maintain. It was annoying to track random exeptions due to some random temp-file removal! How would you handle exceptions for the critical part? Code public class Find { private Stack<File> fs=new Stack<File>(); private Stack<File> ds=new Stack<File>(); public Stack<File> getD(){ return ds;} public Stack<File> getF(){ return fs;} public Find(String path) { // setting this type of special checks due to errs // propagation makes the code clittered if(path==null) { System.out.println("NULL in Find(path)"); System.exit(9); } this.walk(path); } private void walk( String path ) { File root = new File( path ); File[] list = root.listFiles(); //TODO: dangerous with empty try-catch?! try{ for ( File f : list ) { if ( f.isDirectory() ) { walk( f.getAbsolutePath() ); ds.push(f); } else { fs.push(f); } } }catch(Exception e){e.printStackTrace();} } } Code refactored from here.

    Read the article

  • Return value changed after finally

    - by Nestor
    I have the following code: public bool ProcessData(String data) { try { result= CheckData(data); if (TextUtils.isEmpty(result)) { summary="Data is invalid"; return false; } ... finally { Period period = new Period(startTime, new LocalDateTime()); String duration = String.format("Duration: %s:%s", period.getMinutes(), period.getSeconds()); LogCat(duration); } return true; As I learned from this question, the finally block is executed after the return statement. So I modified my code according to that, and in the finally I inserted code that does not modify the output. Strangely, the code OUTSIDE the finally block does. My method always returns true. As suggested, it is not a good idea to have 2 return. What should I do?

    Read the article

  • Exception from within a finally block

    - by schrödingers cat
    Consider the following code where LockDevice() could possibly fail and throw an exception on ist own. What happens in C# if an exception is raised from within a finally block? UnlockDevice(); try { DoSomethingWithDevice(); } finally { LockDevice(); // can fail with an exception }

    Read the article

  • Set reference = null in finally block?

    - by deamon
    A colleague of mine sets reference to null in finally blocks. I think this is nonsense. public Something getSomething() { JDBCConnection jdbc=null; try { jdbc=JDBCManager.getConnection(JDBCTypes.MYSQL); } finally { JDBCManager.free(jdbc); jdbc=null; // <-- Useful or not? } } What do you think of it?

    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

  • How to make a try-catch block that iterates through all objects of a list and keeps on calling a met

    - by aperson
    Basically iterating through a list and, - Invoke method on first object - Catch first exception (if any); if there are no more exceptions to catch, return normally. Otherwise, keep on invoking method until all exceptions are caught. - Move on to next object. I can iterate through each object, invoke the method, and catch one exception but I do not know how to continuously invoke the method on it and keep on catching exceptions :S Thanks :)

    Read the article

  • In Java, does return trump finally?

    - by jonny five
    If I have a try/catch block with returns inside it, will the finally block be called? For example: try { something(); return success; } catch (Exception e) { return failure; } finally { System.out.println "i don't know if this will get printed out." } I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question. Thanks!

    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

  • 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

  • usage of try catch

    - by Muhammed Rauf K
    Which is best: Code Snippet 1 or Code Snippet 2 ? And Why? /* Code Snippet 1 * * Write try-catch in function definition */ void Main(string[] args) { AddMe(); } void AddMe() { try { // Do operations... } catch(Exception e) { } } /* Code Snippet 2 * * Write try-catch where we call the function. */ void Main(string[] args) { try { AddMe(); } catch (Exception e) { } } void AddMe() { // Do operations... }

    Read the article

  • PowerShell Try Catch Finally

    - by PointsToShare
    PowerShell Try Catch Finally I am a relative novice to PowerShell and tried (pun intended) to use the “Try Catch Finally” in my scripts. Alas the structure that we love and use in C# (or even – shudder of shudders - in VB) does not always work in PowerShell. It turns out that it works only when the error is a terminating error (whatever that means). Well, you can turn all your errors to the terminating kind by simply setting - $ErrorActionPreference = "Stop", And later resetting it back to “Continue”, which is its normal setting. Now, the lazy approach is to start all your scripts with: $ErrorActionPreference = "Stop" And ending all of them with: $ErrorActionPreference = "Continue" But this opens you to trouble because should your script have an error that you neglected to catch (it even happens to me!), your session will now have all its errors as “terminating”. Obviously this is not a good thing, so instead let’s put these two setups in the beginning of each Try block and in the Finally block as seen below: That’s All Folks!!

    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

  • Does PHP Try Catch freezes the page?

    - by serhio
    I have the following code function displaySomeFeeds($urls, $keywords = NULL) { error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE); echo "<ul>"; foreach ($urls as $url) { try { displayFeed($url, $keywords, NULL, false); } catch(Exception $e) { //echo "Error when obtaining news from '$url': " .$e->getMessage(); } } echo "</ul>"; } When I use it with Try Catch, the pages loads very, very, very slow. When I use it without Try/Catch the pages loads normally, but with error messages. Could I ammeliorate the time of response with Try/Catch?

    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

  • 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

  • TRY CATCH with Linked Server in SQL Server 2005 Not Working

    - by Robert Stanley
    Hello, I am trying to catch sql error raised when I execute a stored procedure on a linked server. Both Servers are running SQL Server 2005. To prove the issue I have created a stored procedure on the linked server called Raise error that executes the following code: RAISERROR('An error', 16, 1); If I execute the stored procedure directly on the linked server using the following code I get a result set with 'An error', '16' as expected (ie the code enters the catch block): BEGIN TRY EXEC [dbo].[RaiseError]; END TRY BEGIN CATCH DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int; SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY(); SELECT @ErrMsg, @ErrSeverity; END CATCH If I run the following code on my local server to execute the stored procedure on the linked server then SSMS gives me the message 'Query completed with errors', .Msg 50000, Level 16, State 1, Procedure RaiseError, Line 13 An error' BEGIN TRY EXEC [Server].[Catalog].[dbo].RaiseError END TRY BEGIN CATCH DECLARE @SPErrMsg nvarchar(4000), @SPErrSeverity int; SELECT @SPErrMsg = ERROR_MESSAGE(), @SPErrSeverity = ERROR_SEVERITY(); SELECT @SPErrMsg, @SPErrSeverity; END CATCH My Question is can I catch the error generated when the Linked server stored procedure executes? Thanks in advance!

    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

  • 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

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