Search Results

Search found 40287 results on 1612 pages for 'try statement'.

Page 1/1612 | 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

  • Performance of if statement versus switch statement

    - by behrk2
    Hi Everyone, I have an if statement with 16 cases (I am checking the state of four boolean variables). Would there be any value in trying to implement this differently, with nested switch statements perhaps? What is the actual performance gain of a switch statement over an if statement? Thanks!

    Read the article

  • Making a Statement: How to retrieve the T-SQL statement that caused an event

    - by extended_events
    If you’ve done any troubleshooting of T-SQL, you know that sooner or later, probably sooner, you’re going to want to take a look at the actual statements you’re dealing with. In extended events we offer an action (See the BOL topic that covers Extended Events Objects for a description of actions) named sql_text that seems like it is just the ticket. Well…not always – sounds like a good reason for a blog post. When is a statement not THE statement? The sql_text action returns the same information that is returned from DBCC INPUTBUFFER, which may or may not be what you want. For example, if you execute a stored procedure, the sql_text action will return something along the lines of “EXEC sp_notwhatiwanted” assuming that is the statement you sent from the client. Often times folks would like something more specific, like the actual statements that are being run from within the stored procedure or batch. Enter the stack Extended events offers another action, this one with the descriptive name of tsql_stack, that includes the sql_handle and offset information about the statements being run when an event occurs. With the sql_handle and offset values you can retrieve the specific statement you seek using the DMV dm_exec_sql_statement. The BOL topic for dm_exec_sql_statement provides an example for how to extract this information, so I’ll cover the gymnastics required to get the sql_handle and offset values out of the tsql_stack data collected by the action. I’m the first to admit that this isn’t pretty, but this is what we have in SQL Server 2008 and 2008 R2. We will be making it easier to get statement level information in the next major release of SQL Server. The sample code For this example I have a stored procedure that includes multiple statements and I have a need to differentiate between those two statements in my tracing. I’m going to track two events: module_end tracks the completion of the stored procedure execution and sp_statement_completed tracks the execution of each statement within a stored procedure. I’m adding the tsql_stack events (since that’s the topic of this post) and the sql_text action for comparison sake. (If you have questions about creating event sessions, check out Pedro’s post Introduction to Extended Events.) USE AdventureWorks2008GO -- Test SPCREATE PROCEDURE sp_multiple_statementsASSELECT 'This is the first statement'SELECT 'this is the second statement'GO -- Create a session to look at the spCREATE EVENT SESSION track_sprocs ON SERVERADD EVENT sqlserver.module_end (ACTION (sqlserver.tsql_stack, sqlserver.sql_text)),ADD EVENT sqlserver.sp_statement_completed (ACTION (sqlserver.tsql_stack, sqlserver.sql_text))ADD TARGET package0.ring_bufferWITH (MAX_DISPATCH_LATENCY = 1 SECONDS)GO -- Start the sessionALTER EVENT SESSION track_sprocs ON SERVERSTATE = STARTGO -- Run the test procedureEXEC sp_multiple_statementsGO -- Stop collection of events but maintain ring bufferALTER EVENT SESSION track_sprocs ON SERVERDROP EVENT sqlserver.module_end,DROP EVENT sqlserver.sp_statement_completedGO Aside: Altering the session to drop the events is a neat little trick that allows me to stop collection of events while keeping in-memory targets such as the ring buffer available for use. If you stop the session the in-memory target data is lost. Now that we’ve collected some events related to running the stored procedure, we need to do some processing of the data. I’m going to do this in multiple steps using temporary tables so you can see what’s going on; kind of like having to “show your work” on a math test. The first step is to just cast the target data into XML so I can work with it. After that you can pull out the interesting columns, for our purposes I’m going to limit the output to just the event name, object name, stack and sql text. You can see that I’ve don a second CAST, this time of the tsql_stack column, so that I can further process this data. -- Store the XML data to a temp tableSELECT CAST( t.target_data AS XML) xml_dataINTO #xml_event_dataFROM sys.dm_xe_sessions s INNER JOIN sys.dm_xe_session_targets t    ON s.address = t.event_session_addressWHERE s.name = 'track_sprocs' SELECT * FROM #xml_event_data -- Parse the column data out of the XML blockSELECT    event_xml.value('(./@name)', 'varchar(100)') as [event_name],    event_xml.value('(./data[@name="object_name"]/value)[1]', 'varchar(255)') as [object_name],    CAST(event_xml.value('(./action[@name="tsql_stack"]/value)[1]','varchar(MAX)') as XML) as [stack_xml],    event_xml.value('(./action[@name="sql_text"]/value)[1]', 'varchar(max)') as [sql_text]INTO #event_dataFROM #xml_event_data    CROSS APPLY xml_data.nodes('//event') n (event_xml) SELECT * FROM #event_data event_name object_name stack_xml sql_text sp_statement_completed NULL <frame level="1" handle="0x03000500D0057C1403B79600669D00000100000000000000" line="4" offsetStart="94" offsetEnd="172" /><frame level="2" handle="0x01000500CF3F0331B05EC084000000000000000000000000" line="1" offsetStart="0" offsetEnd="-1" /> EXEC sp_multiple_statements sp_statement_completed NULL <frame level="1" handle="0x03000500D0057C1403B79600669D00000100000000000000" line="6" offsetStart="174" offsetEnd="-1" /><frame level="2" handle="0x01000500CF3F0331B05EC084000000000000000000000000" line="1" offsetStart="0" offsetEnd="-1" /> EXEC sp_multiple_statements module_end sp_multiple_statements <frame level="1" handle="0x03000500D0057C1403B79600669D00000100000000000000" line="0" offsetStart="0" offsetEnd="0" /><frame level="2" handle="0x01000500CF3F0331B05EC084000000000000000000000000" line="1" offsetStart="0" offsetEnd="-1" /> EXEC sp_multiple_statements After parsing the columns it’s easier to see what is recorded. You can see that I got back two sp_statement_completed events, which makes sense given the test procedure I’m running, and I got back a single module_end for the entire statement. As described, the sql_text isn’t telling me what I really want to know for the first two events so a little extra effort is required. -- Parse the tsql stack information into columnsSELECT    event_name,    object_name,    frame_xml.value('(./@level)', 'int') as [frame_level],    frame_xml.value('(./@handle)', 'varchar(MAX)') as [sql_handle],    frame_xml.value('(./@offsetStart)', 'int') as [offset_start],    frame_xml.value('(./@offsetEnd)', 'int') as [offset_end]INTO #stack_data    FROM #event_data        CROSS APPLY    stack_xml.nodes('//frame') n (frame_xml)    SELECT * from #stack_data event_name object_name frame_level sql_handle offset_start offset_end sp_statement_completed NULL 1 0x03000500D0057C1403B79600669D00000100000000000000 94 172 sp_statement_completed NULL 2 0x01000500CF3F0331B05EC084000000000000000000000000 0 -1 sp_statement_completed NULL 1 0x03000500D0057C1403B79600669D00000100000000000000 174 -1 sp_statement_completed NULL 2 0x01000500CF3F0331B05EC084000000000000000000000000 0 -1 module_end sp_multiple_statements 1 0x03000500D0057C1403B79600669D00000100000000000000 0 0 module_end sp_multiple_statements 2 0x01000500CF3F0331B05EC084000000000000000000000000 0 -1 Parsing out the stack information doubles the fun and I get two rows for each event. If you examine the stack from the previous table, you can see that each stack has two frames and my query is parsing each event into frames, so this is expected. There is nothing magic about the two frames, that’s just how many I get for this example, it could be fewer or more depending on your statements. The key point here is that I now have a sql_handle and the offset values for those handles, so I can use dm_exec_sql_statement to get the actual statement. Just a reminder, this DMV can only return what is in the cache – if you have old data it’s possible your statements have been ejected from the cache. “Old” is a relative term when talking about caches and can be impacted by server load and how often your statement is actually used. As with most things in life, your mileage may vary. SELECT    qs.*,     SUBSTRING(st.text, (qs.offset_start/2)+1,         ((CASE qs.offset_end          WHEN -1 THEN DATALENGTH(st.text)         ELSE qs.offset_end         END - qs.offset_start)/2) + 1) AS statement_textFROM #stack_data AS qsCROSS APPLY sys.dm_exec_sql_text(CONVERT(varbinary(max),sql_handle,1)) AS st event_name object_name frame_level sql_handle offset_start offset_end statement_text sp_statement_completed NULL 1 0x03000500D0057C1403B79600669D00000100000000000000 94 172 SELECT 'This is the first statement' sp_statement_completed NULL 1 0x03000500D0057C1403B79600669D00000100000000000000 174 -1 SELECT 'this is the second statement' module_end sp_multiple_statements 1 0x03000500D0057C1403B79600669D00000100000000000000 0 0 C Now that looks more like what we were after, the statement_text field is showing the actual statement being run when the sp_statement_completed event occurs. You’ll notice that it’s back down to one row per event, what happened to frame 2? The short answer is, “I don’t know.” In SQL Server 2008 nothing is returned from dm_exec_sql_statement for the second frame and I believe this to be a bug; this behavior has changed in the next major release and I see the actual statement run from the client in frame 2. (In other words I see the same statement that is returned by the sql_text action  or DBCC INPUTBUFFER) There is also something odd going on with frame 1 returned from the module_end event; you can see that the offset values are both 0 and only the first letter of the statement is returned. It seems like the offset_end should actually be –1 in this case and I’m not sure why it’s not returning this correctly. This behavior is being investigated and will hopefully be corrected in the next major version. You can workaround this final oddity by ignoring the offsets and just returning the entire cached statement. SELECT    event_name,    sql_handle,    ts.textFROM #stack_data    CROSS APPLY sys.dm_exec_sql_text(CONVERT(varbinary(max),sql_handle,1)) as ts event_name sql_handle text sp_statement_completed 0x0300070025999F11776BAF006F9D00000100000000000000 CREATE PROCEDURE sp_multiple_statements AS SELECT 'This is the first statement' SELECT 'this is the second statement' sp_statement_completed 0x0300070025999F11776BAF006F9D00000100000000000000 CREATE PROCEDURE sp_multiple_statements AS SELECT 'This is the first statement' SELECT 'this is the second statement' module_end 0x0300070025999F11776BAF006F9D00000100000000000000 CREATE PROCEDURE sp_multiple_statements AS SELECT 'This is the first statement' SELECT 'this is the second statement' Obviously this gives more than you want for the sp_statement_completed events, but it’s the right information for module_end. I leave it to you to determine when this information is needed and use the workaround when appropriate. Aside: You might think it’s odd that I’m showing apparent bugs with my samples, but you’re going to see this behavior if you use this method, so you need to know about it.I’m all about transparency. Happy Eventing- Mike Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

    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

  • Short circuiting statement evaluation -- is this guaranteed? [C#]

    - by larryq
    Hi everyone, Quick question here about short-circuiting statements in C#. With an if statement like this: if (MyObject.MyArray.Count == 0 || MyObject.MyArray[0].SomeValue == 0) { //.... } Is it guaranteed that evaluation will stop after the "MyArray.Count" portion, provided that portion is true? Otherwise I'll get a null exception in the second part.

    Read the article

  • Prepared statement help, Number of variables doesn't match number of parameters in prepared statement

    - by Sam Gabriel
    I'm getting this error : Number of variables doesn't match number of parameters in prepared statement every time I run this code: $dbh = new mysqli("localhost", "***", "***", "pics"); $stmt = $dbh->prepare("INSERT INTO comments (username, picture, comment) VALUES (?, ?, ?)"); $stmt->bind_Param('s', $username); $stmt->bind_Param('d', $picture); $stmt->bind_Param('s', $comment); $username=$_SESSION['username']; $picture=$_GET['id']; $comment=$_POST['comment']; $stmt->execute(); What's the problem?

    Read the article

  • Using a Case statement within the values section of an Insert statement

    - by mattgcon
    Please forgive my ignorance and poor SQL programming skills but I am normally a basic SQL developer. I need to create a trigger off the insertion of data in one table to insert different data into another table. Within this trigger I need to insert certain data into the new table based upon values within the newly inserted data from the original table. I am totally confused on this. i thought I would be creative and use a case statement within teh Values section but it is not working. Can anyone please help me on this? (below is the code for the trigger that I have as of now) INSERT INTO dbo.WebOnlineUserPeopleDashboard ( ONLINE_USERACCOUNT_ID, ONLINE_ROOMS_DIRECTORY, ONLINE_ROOMS_LIST, ONLINE_ROOMS_PLACEMENT, ONLINE_ROOMS_MANAGEMENT, ONLINE_MAILINGLIST_DIRECTORY, ONLINE_MAILINGLIST_LIST, ONLINE_MAILINGLIST_MEMBERS, ONLINE_MAILINGLIST_MANAGER, ONLINE_PEOPLESEARCH_DIRECTORY ) VALUES IF (SELECT ONLINE_PEOPLE_FULL_ACCESS FROM INSERTED) = 1 BEGIN SELECT ONLINE_USERACCOUNT_ID, 1, 1, 1, 1, 1, 1, 1, 1, 1 FROM INSERTED END ELSE IF (SELECT ONLINE_PEOPLE_FULL_ACCESS FROM INSERTED) = 0 BEGIN SELECT ONLINE_USERACCOUNT_ID, 0, 0, 0, 0, 0, 0, 0, 0, 0 FROM INSERTED END ELSE BEGIN SELECT ONLINE_USERACCOUNT_ID, CASE --DIRECTORY WHEN ONLINE_PEOPLE_ROOMS_PLACEMENT_FULL_ACCESS = 1 OR ONLINE_PEOPLE_ROOMS_PLACEMENT_VIEW = 1 OR ONLINE_PEOPLE_ROOMS_PLACEMENT_ADD = 1 OR ONLINE_PEOPLE_ROOMS_PLACEMENT_UPDATE = 1 OR ONLINE_PEOPLE_ROOMS_PLACEMENT_DELETE = 1 THEN 1 WHEN ONLINE_PEOPLE_ROOMS_PLACEMENT_FULL_ACCESS = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_ROOMS_PLACEMENT_VIEW = 1 THEN 1 WHEN ONLINE_PEOPLE_ROOMS_PLACEMENT_VIEW = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_ROOMS_PLACEMENT_ADD = 1 OR ONLINE_PEOPLE_ROOMS_PLACEMENT_UPDATE = 1 OR ONLINE_PEOPLE_ROOMS_PLACEMENT_DELETE = 1 THEN 1 WHEN ONLINE_PEOPLE_ROOMS_PLACEMENT_ADD = 0 AND ONLINE_PEOPLE_ROOMS_PLACEMENT_UPDATE = 0 AND ONLINE_PEOPLE_ROOMS_PLACEMENT_DELETE = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_ROOMS_MANAGEMENT_FULL_ACCESS = 1 THEN 1 WHEN ONLINE_PEOPLE_ROOMS_MANAGEMENT_FULL_ACCESS = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_MAILING_LISTS_FULL_ACCESS = 1 OR ONLINE_PEOPLE_MAILING_LISTS_VIEW = 1 OR ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_ADD = 1 OR ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_UPDATE = 1 OR ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_DELETE = 1 THEN 1 WHEN ONLINE_PEOPLE_MAILING_LISTS_FULL_ACCESS = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_MAILING_LISTS_VIEW = 1 THEN 1 WHEN ONLINE_PEOPLE_MAILING_LISTS_VIEW = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_ADD = 1 OR ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_UPDATE = 1 OR ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_DELETE = 1 THEN 1 WHEN ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_ADD = 0 AND ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_UPDATE = 0 AND ONLINE_PEOPLE_MAILING_LISTS_MEMBERS_DELETE = 0 THEN 0 END, CASE WHEN ONLINE_PEOPLE_MAILING_LISTS_ADD = 1 OR ONLINE_PEOPLE_MAILING_LISTS_UPDATE = 1 OR ONLINE_PEOPLE_MAILING_LISTS_DELETE = 1 THEN 1 WHEN ONLINE_PEOPLE_MAILING_LISTS_ADD = 1 OR ONLINE_PEOPLE_MAILING_LISTS_UPDATE = 1 OR ONLINE_PEOPLE_MAILING_LISTS_DELETE = 1 THEN 0 END, CASE WHEN ONLINE_PEOPLE_PEOPLE_SEARCH = 1 THEN 1 WHEN ONLINE_PEOPLE_PEOPLE_SEARCH = 0 THEN 0 END FROM INSERTED END END

    Read the article

  • switch statement in for loop and if statement not completing

    - by user2373912
    I'm trying to find out how many of each character are in a string. I've searched around for a while and can't seem to figure out why my switch statement is stopping after the first case. function charFreq(string){ var splitUp = string.split(""); console.log(splitUp); var a; var b; var c; var v; for (var i = 0; i<splitUp.length; i++){ if (i<1){ switch (splitUp[i]){ case "a": a = 1; break; case "b": b = 1; break; case "c": c = 1; break; case "v": v = 1; break; } } else { switch (splitUp[i]){ case "a": a += 1; break; case "b": b += 1; break; case "c": c += 1; break; case "v": v += 1; break; } } } console.log("There are " + a + " A's, " + b + " B's, " + c + " C's, and " + v + " V's.") } charFreq("aaabccbbavabac"); What am I doing wrong that would make the console read: There are 6 A's, NaN B's, NaN C's, and NaN V's.

    Read the article

  • If statement within If statement's else

    - by maebe
    Still new to Java/android so trying to figure out the best way to code a multilevel if statement. What I'm trying to do is for a combat system that needs to check if player/npc is alive. If they are alive it then will check to see if they scored a critical hit. If they didn't critical hit then will see if they hit or missed. combat = mydbhelper.getCombat(); startManagingCursor(combat); if(playerCurHp == 0){ combat.moveToPosition(11); npcCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} else{ if(playerCritFlag.equals("Critical")){ combat.moveToPosition(2); playerCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} else{ if(playerHitFlag.equals("Hit")){ combat.moveToPosition(1); playerCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} if(playerHitFlag.equals("Miss")){ combat.moveToPosition(3); playerCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} }} if (npcCurHp == 0){ combat.moveToPosition(10); npcCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} else{ if(npcCritFlag.equals("Critical")){ combat.moveToPosition(5); npcCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} else{ if(npcHitFlag.equals("Hit")){ combat.moveToPosition(4); npcCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} if(npcHitFlag.equals("Miss")){ combat.moveToPosition(6); npcCombatStory = combat.getString(combat.getColumnIndex(dbhelper.KEY_COMBATDESC));} }} } Is what I'm using. Was working when I had the if statements all separate. But it would check each one and do actions I don't need (If they hit, pull String, if crit pull another, then if dead pull again). Trying to make it stop when it finds the "Flag" that matches. When doing my rolls if the player hits it sets the flag to "Hit" like below code. Random attackRandom = new Random(); int attackRoll = attackRandom.nextInt(100); totalAtt = attackRoll + bonusAttack + weaponAtt + stanceAtt; Random defensiveRandom = new Random(); int defenseRoll = defensiveRandom.nextInt(100); npcDef = defenseRoll + npcDodge + npcBonusDodge; if (totalAtt > npcDef){ playerHitFlag = "Hit"; playerDamage();} else{playerHitFlag = "Miss"; npcAttack();} At the end it takes these playerCombatStory and npcCombatStory strings and uses them to setText to show the player what happened on that turn of combat.

    Read the article

  • What if(event) statement means in JavaScript?

    - by j flo
    I'm rather new to JavaScript and programming in general so I am pretty much only used to seeing if statements that have some kind of comparison operator like, if (x < 10) or if(myBool). I have seen an if statement checking against an event, but I don't understand what or why the event is being checked like that. What's the semantic meaning behind that check or comparison? Here is the code in question: if(event){ event.preventDefault(); }

    Read the article

  • If statement is ignored

    - by user2898120
    I am making a simple matchmaker as a learning project in JAVA. My program so far just asks a few questions, but I wanted to do gender specific questions, so I asked for their sex (m or f) and then attempted to add a message that only showed if sex was m. The dialog should say "well done, you are male!". Else it restarts method. Every time, no matter what I type it restarts the program. Here is my code: import javax.swing.JOptionPane; public class Main { public static void main(String[] args){ setVars(); } public static void setVars(){ String name = JOptionPane.showInputDialog(null, "What is your name?"); String sAge = JOptionPane.showInputDialog(null, "What is your age?"); String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)"); if (sex == "m"){ JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!"); } int age = Integer.parseInt(sAge); String chars = JOptionPane.showInputDialog(null, "Name three charectaristics"); } }

    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

  • Why is there never any controversy regarding the switch statement? [closed]

    - by Nick Rosencrantz
    We all know that the gotostatement should only be used on very rare occasions if at all. It has been discouraged to use the goto statement countless places countless times. But why it there never anything like that about the switch statement? I can understand the position that the switch statement should always be avoided since anything with switch can always be expressed by if...else... which is also more readable and the syntax of the switch statement if difficult to remember. Do you agree? What are the arguments in favor of keeping the 'switch` statement? It can also be difficult to use if what you're testing changes from say an integer to an object, then C++ or Java won't be able to perform the switch and neither C can perform switch on something like a struct or a union. And the technique of fall-through is so very rarely used that I wonder why it was never presented any regret of having switch at all? The only place I know where it is best practice is GUI code and even that switch is probably better coded in a more object-oriented way.

    Read the article

  • T-SQL (SCD) Slowly Changing Dimension Type 2 using a merge statement

    - by AtulThakor
    Working on stored procedure recently which loads records into a data warehouse I found that the existing record was being expired using an update statement followed by an insert to add the new active record. Playing around with the merge statement you can actually expire the current record and insert a new record within one clean statement. This is how the statement works, we do the normal merge statement to insert a record when there is no match, if we match the record we update the existing record by expiring it and deactivating. At the end of the merge statement we use the output statement to output the staging values for the update,  we wrap the whole merge statement within an insert statement and add new rows for the records which we inserted. I’ve added the full script at the bottom so you can paste it and play around.   1: INSERT INTO ExampleFactUpdate 2: (PolicyID, 3: Status) 4: SELECT -- these columns are returned from the output statement 5: PolicyID, 6: Status 7: FROM 8: ( 9: -- merge statement on unique id in this case Policy_ID 10: MERGE dbo.ExampleFactUpdate dp 11: USING dbo.ExampleStag s 12: ON dp.PolicyID = s.PolicyID 13: WHEN NOT MATCHED THEN -- when we cant match the record we insert a new record record and this is all that happens 14: INSERT (PolicyID,Status) 15: VALUES (s.PolicyID, s.Status) 16: WHEN MATCHED --if it already exists 17: AND ExpiryDate IS NULL -- and the Expiry Date is null 18: THEN 19: UPDATE 20: SET 21: dp.ExpiryDate = getdate(), --we set the expiry on the existing record 22: dp.Active = 0 -- and deactivate the existing record 23: OUTPUT $Action MergeAction, s.PolicyID, s.Status -- the output statement returns a merge action which can 24: ) MergeOutput -- be insert/update/delete, on our example where a record has been updated (or expired in our case 25: WHERE -- we'll filter using a where clause 26: MergeAction = 'Update'; -- here   Complete source for example 1: if OBJECT_ID('ExampleFactUpdate') > 0 2: drop table ExampleFactUpdate 3:  4: Create Table ExampleFactUpdate( 5: ID int identity(1,1), 3: go 6: PolicyID varchar(100), 7: Status varchar(100), 8: EffectiveDate datetime default getdate(), 9: ExpiryDate datetime, 10: Active bit default 1 11: ) 12:  13:  14: insert into ExampleFactUpdate( 15: PolicyID, 16: Status) 17: select 18: 1, 19: 'Live' 20:  21: /*Create Staging Table*/ 22: if OBJECT_ID('ExampleStag') > 0 23: drop table ExampleStag 24: go 25:  26: /*Create example fact table */ 27: Create Table ExampleStag( 28: PolicyID varchar(100), 29: Status varchar(100)) 30:  31: --add some data 32: insert into ExampleStag( 33: PolicyID, 34: Status) 35: select 36: 1, 37: 'Lapsed' 38: union all 39: select 40: 2, 41: 'Quote' 42:  43: select * 44: from ExampleFactUpdate 45:  46: select * 47: from ExampleStag 48:  49:  50: INSERT INTO ExampleFactUpdate 51: (PolicyID, 52: Status) 53: SELECT -- these columns are returned from the output statement 54: PolicyID, 55: Status 56: FROM 57: ( 58: -- merge statement on unique id in this case Policy_ID 59: MERGE dbo.ExampleFactUpdate dp 60: USING dbo.ExampleStag s 61: ON dp.PolicyID = s.PolicyID 62: WHEN NOT MATCHED THEN -- when we cant match the record we insert a new record record and this is all that happens 63: INSERT (PolicyID,Status) 64: VALUES (s.PolicyID, s.Status) 65: WHEN MATCHED --if it already exists 66: AND ExpiryDate IS NULL -- and the Expiry Date is null 67: THEN 68: UPDATE 69: SET 70: dp.ExpiryDate = getdate(), --we set the expiry on the existing record 71: dp.Active = 0 -- and deactivate the existing record 72: OUTPUT $Action MergeAction, s.PolicyID, s.Status -- the output statement returns a merge action which can 73: ) MergeOutput -- be insert/update/delete, on our example where a record has been updated (or expired in our case 74: WHERE -- we'll filter using a where clause 75: MergeAction = 'Update'; -- here 76:  77:  78: select * 79: from ExampleFactUpdate 80: 

    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

  • Variable amount of columns returned in mysqli prepared statement

    - by manyxcxi
    I have a situation where a dynamic query is being generated that could select anywhere from 1 to over 300 different columns across multiple tables. It currently works fine just doing a query, however the issue I'm running into in using a prepared statement is that I do not know how to handle the fact that I don't know how many columns I will be asking for each time and therefor don't know how to process the results. The reason I believe a bind statement will help is because once this query is run once, it will most likely (though not always) be run again with the exact same parameters. Currently I have something like this: $rows = array(); $this->statement = $this->db->prepare($query); $this->statement->bind_param('i',$id); $this->statement->execute(); $this->statement->bind_result($result); while($this->statement->fetch()) { $rows[] = $result; } I know this doesn't work as I want it to, my question is how do I get the data back out of the query. Is it possible to bring the columns back in an associative array by column name, like a standard mysqli query?

    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

  • CASE statement within WHERE statement

    - by niao
    Greetings, I would like to include CASE Statement inside my where statement as follows: SELECT a1.ROWGUID FROM Table1 a1 INNER JOIN Table2 a2 on a1.ROWGUID=a2.Table1ROWGUID WHERE a1.Title='title' AND (CASE WHEN @variable is not null THEN a1.ROWGUID in (SELECT * FROM #TempTable)) However, this 'CASE' statement does not work inside 'WHERE' statement. How can I do it correct?

    Read the article

  • Try a sample: Using the counter predicate for event sampling

    - by extended_events
    Extended Events offers a rich filtering mechanism, called predicates, that allows you to reduce the number of events you collect by specifying criteria that will be applied during event collection. (You can find more information about predicates in Using SQL Server 2008 Extended Events (by Jonathan Kehayias)) By evaluating predicates early in the event firing sequence we can reduce the performance impact of collecting events by stopping event collection when the criteria are not met. You can specify predicates on both event fields and on a special object called a predicate source. Predicate sources are similar to action in that they typically are related to some type of global information available from the server. You will find that many of the actions available in Extended Events have equivalent predicate sources, but actions and predicates sources are not the same thing. Applying predicates, whether on a field or predicate source, is very similar to what you are used to in T-SQL in terms of how they work; you pick some field/source and compare it to a value, for example, session_id = 52. There is one predicate source that merits special attention though, not just for its special use, but for how the order of predicate evaluation impacts the behavior you see. I’m referring to the counter predicate source. The counter predicate source gives you a way to sample a subset of events that otherwise meet the criteria of the predicate; for example you could collect every other event, or only every tenth event. Simple CountingThe counter predicate source works by creating an in memory counter that increments every time the predicate statement is evaluated. Here is a simple example with my favorite event, sql_statement_completed, that only collects the second statement that is run. (OK, that’s not much of a sample, but this is for demonstration purposes. Here is the session definition: CREATE EVENT SESSION counter_test ON SERVERADD EVENT sqlserver.sql_statement_completed    (ACTION (sqlserver.sql_text)    WHERE package0.counter = 2)ADD TARGET package0.ring_bufferWITH (MAX_DISPATCH_LATENCY = 1 SECONDS) You can find general information about the session DDL syntax in BOL and from Pedro’s post Introduction to Extended Events. The important part here is the WHERE statement that defines that I only what the event where package0.count = 2; in other words, only the second instance of the event. Notice that I need to provide the package name along with the predicate source. You don’t need to provide the package name if you’re using event fields, only for predicate sources. Let’s say I run the following test queries: -- Run three statements to test the sessionSELECT 'This is the first statement'GOSELECT 'This is the second statement'GOSELECT 'This is the third statement';GO Once you return the event data from the ring buffer and parse the XML (see my earlier post on reading event data) you should see something like this: event_name sql_text sql_statement_completed SELECT ‘This is the second statement’ You can see that only the second statement from the test was actually collected. (Feel free to try this yourself. Check out what happens if you remove the WHERE statement from your session. Go ahead, I’ll wait.) Percentage Sampling OK, so that wasn’t particularly interesting, but you can probably see that this could be interesting, for example, lets say I need a 25% sample of the statements executed on my server for some type of QA analysis, that might be more interesting than just the second statement. All comparisons of predicates are handled using an object called a predicate comparator; the simple comparisons such as equals, greater than, etc. are mapped to the common mathematical symbols you know and love (eg. = and >), but to do the less common comparisons you will need to use the predicate comparators directly. You would probably look to the MOD operation to do this type sampling; we would too, but we don’t call it MOD, we call it divides_by_uint64. This comparator evaluates whether one number is divisible by another with no remainder. The general syntax for using a predicate comparator is pred_comp(field, value), field is always first and value is always second. So lets take a look at how the session changes to answer our new question of 25% sampling: CREATE EVENT SESSION counter_test_25 ON SERVERADD EVENT sqlserver.sql_statement_completed    (ACTION (sqlserver.sql_text)    WHERE package0.divides_by_uint64(package0.counter,4))ADD TARGET package0.ring_bufferWITH (MAX_DISPATCH_LATENCY = 1 SECONDS)GO Here I’ve replaced the simple equivalency check with the divides_by_uint64 comparator to check if the counter is evenly divisible by 4, which gives us back every fourth record. I’ll leave it as an exercise for the reader to test this session. Why order matters I indicated at the start of this post that order matters when it comes to the counter predicate – it does. Like most other predicate systems, Extended Events evaluates the predicate statement from left to right; as soon as the predicate statement is proven false we abandon evaluation of the remainder of the statement. The counter predicate source is only incremented when it is evaluated so whether or not the counter is incremented will depend on where it is in the predicate statement and whether a previous criteria made the predicate false or not. Here is a generic example: Pred1: (WHERE statement_1 AND package0.counter = 2)Pred2: (WHERE package0.counter = 2 AND statement_1) Let’s say I cause a number of events as follows and examine what happens to the counter predicate source. Iteration Statement Pred1 Counter Pred2 Counter A Not statement_1 0 1 B statement_1 1 2 C Not statement_1 1 3 D statement_1 2 4 As you can see, in the case of Pred1, statement_1 is evaluated first, when it fails (A & C) predicate evaluation is stopped and the counter is not incremented. With Pred2 the counter is evaluated first, so it is incremented on every iteration of the event and the remaining parts of the predicate are then evaluated. In this example, Pred1 would return an event for D while Pred2 would return an event for B. But wait, there is an interesting side-effect here; consider Pred2 if I had run my statements in the following order: Not statement_1 Not statement_1 statement_1 statement_1 In this case I would never get an event back from the system because the point at which counter=2, the rest of the predicate evaluates as false so the event is not returned. If you’re using the counter target for sampling and you’re not getting the expected events, or any events, check the order of the predicate criteria. As a general rule I’d suggest that the counter criteria should be the last element of your predicate statement since that will assure that your sampling rate will apply to the set of event records defined by the rest of your predicate. Aside: I’m interested in hearing about uses for putting the counter predicate criteria earlier in the predicate statement. If you have one, post it in a comment to share with the class. - Mike Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

    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

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