Query AD cause Exception calling "FindAll" with "0" argument(s)
Hi all,
When I query an entry property of AD with PowerShell, i got some problems. Here is the script, what's wrong ? Any idea? Thanks!
Cause error at last line code. (Exception calling "FindAll" with "0" argument(s): "There is no such object on the server)
$MailboxServer = Get-MailboxServer -Identity $Env:COMPUTERNAME -ErrorAction SilentlyContinue
$dc = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$exchOAB = New-Object System.DirectoryServices.DirectoryEntry("LDAP://" + $dc.Name + "/cn=Offline Address Lists,cn=Address Lists Container, " + $MailboxServer.DistinguishedName)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $exchOAB
$objSearcher.PageSize = 1000
$objSearcher.SearchScope = "OneLevel"
$objSearcher.Filter = "(objectClass=msExchOAB)"
$powershellOAB = $objSearcher.FindAll()
This is one of, now, four duplicate posts.
¯\_(ツ)_/¯
Similar Messages
-
Hi,
I have a Sharepoint 2013 farm I am trying to provision search for (not the same as my other thread). However, I get the below error:
Exception calling "Activate" with "0" argument(s): "Topology does not contain any components of type Microsoft.Office.Server.Search.Administration.Topology.AdminComponent"
In my script, I have the following:
New-SPEnterpriseSearchAdminComponent -SearchTopology $clone -SearchServiceInstance $SearchServiceInstanceServer3 -ErrorAction SilentlyContinue
So I am not sure why the error happens, when I am trying to set this component. However, it's not the first component to be set (index partition on non-local servers first). I can make it first, but why does this error happen?
UPDATE: I have noticed that the usage and health proxy on my farm is/was stopped, but I am not able to access the server(s) to look at this right now. Could this cause this issue?Do you already have Admin component running for the Search Service Application?
Usage and Health Service will not cause this issue.
Please also refer to below discussion to see if it helps:
http://social.technet.microsoft.com/Forums/sharepoint/en-US/02f0b072-aa3a-4b7f-9662-2caf373d1e57/setspenterprisesearchtopology-identity-newtopology?forum=sharepointgeneral
Warm Regards,
Bhavik K Jain
Sr. Software Engineer - SharePoint Administration
Please vote if my reply helps and ensure that you mark a question as Answered once you receive a satisfactory response. -
Hi i am trying to add a new item and update existing field value in a document library with powershell
but i receive below error message.
PS C:\Users\spfarm> C:\Scripts\add.ps1
Exception calling "Update" with "0" argument(s): "To add an item to a document
library, use SPFileCollection.Add()"
At C:\Scripts\add.ps1:24 char:16
+ $newItem.Update <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
#Add SharePoint PowerShell Snapin which adds SharePoint specific cmdlets
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
#Variables that we are going to use for list editing
$webURL = "http://tspmcwfe:89"
$listName = "test"
#Get the SPWeb object and save it to a variable
$web = Get-SPWeb $webURL
#Get the SPList object to retrieve the "Demo List"
$list = $web.Lists[$listName]
#Create a new item
$newItem = $list.Items.Add()
#Add properties to this list item
$newItem["Title"] = "My second item!"
$newItem["Info"] = "s15"
#Update the object so it gets saved to the list
$newItem.Update()
$web.Dispose()
adilHi Adil,
Document Library is different from a normal list. The document library contains files inside it. You need to update the code to add a document to the library. Then you can get hold of the List Item represented by that file and update its properties. Here
is an example:
$WebURL = "http://aissp2013/sites/TestSite"
$DocLibName = "Docs"
$FilePath = "c:\blogs.txt"
# Get a variable that points to the folder
$Web = Get-SPWeb $WebURL
$List = $Web.GetFolder($DocLibName)
$Files = $List.Files
# Get just the name of the file from the whole path
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
# Load the file into a variable
$File= Get-ChildItem $FilePath
# Upload it to SharePoint
$spFile = $Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$false)
$item = $spFile.Item
$item["Title"] = "New Title"
$item.Update()
$web.Dispose()
Blog | SharePoint Learnings CodePlex Tools |
Export Version History To Excel |
Autocomplete Lookup Field -
Hi,
I am getting an error System.Management.Automation.MethodInvocationException: Exception calling "ExecuteQuery" with "0" argument(s): "$Resources:core,ImportErrorMessage;" ---> Microsoft.SharePoint.Client. ServerException:
$Resources:core,ImportErrorMessage;
Following is my powershell script on line
$context.ExecuteQuery(); it is throwing this error.
function AddWebPartToPage([string]$siteUrl,[string]$pageRelativeUrl,[string]$localWebpartPath,[string]$ZoneName,[int]$ZoneIndex)
try
#this reference is required here
$clientContext= [Microsoft.SharePoint.Client.ClientContext,Microsoft.SharePoint.Client, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c]
$context=New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
write-host "Reading file " $pageRelativeUrl
$oFile = $context.Web.GetFileByServerRelativeUrl($pageRelativeUrl);
$limitedWebPartManager = $oFile.GetLimitedWebPartManager([Microsoft.Sharepoint.Client.WebParts.PersonalizationScope]::Shared);
write-host "getting xml reader from file"
$xtr = New-Object System.Xml.XmlTextReader($localWebpartPath)
[void] [Reflection.Assembly]::LoadWithPartialName("System.Text")
$sb = new-object System.Text.StringBuilder
while ($xtr.Read())
$tmpObj = $sb.AppendLine($xtr.ReadOuterXml());
$newXml = $sb.ToString()
if ($xtr -ne $null)
$xtr.Close()
#Add Web Part to catalogs folder
write-host "Adding Webpart....."
$oWebPartDefinition = $limitedWebPartManager.ImportWebPart($newXml);
$limitedWebPartManager.AddWebPart($oWebPartDefinition.WebPart, $ZoneName, $ZoneIndex);
$context.ExecuteQuery();
write-host "Adding Web Part Done"
catch
write-host "Error while 'AddWebPartToPage'" $_.exception| format-list * -force
ERROR:
Error while 'AddWebPartToPage' System.Management.Automation.MethodInvocationException: Exception calling "ExecuteQuery" with "0" argument(s): "$Resources:core,ImportErrorMessage;" ---> Microsoft.SharePoint.Client.
ServerException: $Resources:core,ImportErrorMessage;
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at ExecuteQuery(Object , Object[] )
at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments)
--- End of inner exception stack trace ---
at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments)
at System.Management.Automation.DotNetAdapter.MethodInvokeDotNet(String methodName, Object target, MethodInformation[] methodInformation, Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.ParserOps.CallMethod(Token token, Object target, String methodName, Object[] paramArray, Boolean callStatic, Object valueToSet)
at System.Management.Automation.MethodCallNode.InvokeMethod(Object target, Object[] arguments, Object value)
at System.Management.Automation.MethodCallNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
Thanks Sethu for your comments. However i am running this powershell directly on server so believe
SharePointOnlineCredentials is not required.
I have tried it but still giving me same error -
I have CSV file which has sdimiler data I am inserting those date to desinated table and while executing this query mentioned below I get error mentioned in TITLE
insert into SU_EDIT_DETAIL(EDIT_FUNCTION, TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS)"
select $($line."EDIT_FUNCTION"),($line."TABLE_FUNCTION"), ($line."CODE_FUNCTION"),'DIAG', ($line."CODE_BEGIN"), ($line."CODE_END"),' ',' ',' ','MIS', 'C',' ',20141001, 99991231, 20131120
from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = ($line."EDIT_FUNCTION") and TABLE_FUNCTION = ($line."TABLE_FUNCTION")
and CODE_BEGIN= ($line."CODE_BEGIN")
and CODE_END= ($line."CODE_END")));
commit;
Vijay PatelThis SQL appears to be Oracle PL/SQL. You may want to post in the Oracle forum. If you are habving issues with the ADO.NET objects then you need to supply more of your code.
¯\_(ツ)_/¯ -
Call function with select arguments
Hi Gurus,
I have problem to call function inside select statements as follow:
select a.ID_ELE2, a.ID_ELE3, a.DT_FIS_YR, c.NU_FIS_PER, c.dt,
(case
when c.ld is null then
GET_LD_CHECK (a.DT_FIS_YR,c.NU_FIS_PER, a.ID_ELE3, a.ID_ELE2) -- 1
-- GET_LD_CHECK ('2009',7, '8010', '7493') --- 2
else
c.ld
end ) description
from ACCOUNT a, TRANSACTION c
where a.DT_FIS_YR ='2009'
and a.ID_ELE3 <> '0000'
and c.TY_SRC not in ('CL', 'CN')
and a.DT_FIS_YR = c.nu_fis_yr
and a.AK = c.AK_FGCHAR
and trim(a.ID_ELE3) ='8010'
and c.NU_FIS_PER <> 14
order by 1,4,5,6
the 1 doesn't output result but the 2 it does! How can pass the select result to the function?
Thanks in advance for your help.
BenThe statement / function call seems to be ok. So there are not much chances left for your call to return different (=non) values.
1) It could be that you have different values in the column then during your test call.
2) Maybe your function raises an error and that error is supressed in some ugly WHEN OTHERS EXCEPTION => Solution: Get rid of the error handler.
3) datatype conversion. For example if a.dt_fis_yr is a number value, then you should test with number values and not with strings. GET_LD_CHECK (2009,7, '8010', '7493'). Same logic goes for the other paramters, make sure the datatype is correct and matches the function parameter. -
Call method with an argument from another view controller
I have a UIViewController MainViewController that brings up a modal view that is of the class AddPlayerViewController. When the user clicks 'Save' in the modal view I need to pass the Player data (which is a Player class) from the modal view to the MainViewController in addition to triggering a method in the MainViewController. What's the best way to accomplish this? I'm new to cocoa and have only tried using delegates and some ugly hacks to no avail.
Thanks for the help.If I understand correctly, you have:
1. A model object, Player.
2. A top view controller, MainViewController.
3. Another view controller, AddPlayerViewController, which MainViewController displays modally.
I'm guessing that AddPlayerViewController creates a new Player object and lets the user set its values, and you need a way to get that new Player into MainViewController once they're done.
So, here's what I'd do:
1. Create an AddPlayerViewControllerDelegate protocol. It should declare two methods, "- (void)addPlayerViewController:(AddPlayerViewContrller*)controller didAddPlayer:(Player*)newPlayer" and "- (void)addPlayerViewControllerNotAddingPlayer:(AddPlayerViewController*)controll er".
2. Add an attribute of type "id <AddPlayerViewControllerDelegate>" called delegate to AddPlayerViewController. Also add a property with "@property (assign)" and "@synthesize".
3. Modify AddPlayerViewController so that if you click the "Save" button, addPlayerViewController:didAddPlayer: gets called, passing "self" and the new Player object as the two arguments. Also arrange for clicking the "Cancel" button to call addPlayerViewControllerNotAddingPlayer:.
4. Modify MainViewController to declare that it conforms to AddPlayerViewControllerDelegate. Implement those two methods (addPlayerViewControllerNotAddingPlayer: might be an empty method if you don't want to do anything).
5. When you create your AddPlayerViewController, set its delegate to your MainViewController.
If you need more detail, let me know what parts you need me to elaborate on. -
Calling RH_ShowLocalHelp with 5 arguments
Hello all,
I'm trying to make a context-sensitive help call from C#. According to the documentation at http://help.adobe.com/en_US/robohelp/robohtml/WS5b3ccc516d4fbf351e63e3d11aff59c571-7f39.ht ml , there's a function named RH_ShowLocalHelp that takes 5 parameters. Unfortunately, that function seems to be missing from the C# files that ship with RoboHelp 10 (the 4 arguments' version is in the file, though). Am I missing something in here? Am I not using the right files?
Thanks in advance,
--IgnacioI don't have an answer but maybe a look at www.wvanweelden.eu will help. Willam has a lot of information on calling help.
See www.grainge.org for RoboHelp and Authoring tips
@petergrainge -
Call apt with multiple arguments
Is it possible to call apt inside a java class and pass multiple .class files?
For example:
String[] args = new String[5];
args[0] = "-nowarn";
args[1] = "-XclassesAsDecls";
args[2] = "-classpath";
args[3] = System.getProperty("java.class.path");
args[4] = "packageName.FirstClass packageName.SecondClass";
return Main.process(new MyAnnotationProcessorFactory(),args);Result of the above example is:
error: Could not find class file for packageName.FirstClass packageName.SecondClass
1 errorThe class path contains classes that we need.
This example works:
String[] args = new String[6];
args[0] = "-nowarn";
args[1] = "-XclassesAsDecls";
args[2] = "-classpath";
args[3] = System.getProperty("java.class.path");
args[4] = "packageName.FirstClass";
args[5] = "packageName.SecondClass";
return Main.process(new IapiAnnotationProcessorFactory(),args);I replaced args[4] = "packageName.FirstClass packageName.SecondClass"; with a
args[4] = "packageName.FirstClass";
args[5] = "packageName.SecondClass"; -
How to call function with varray arguments .
Hi,
I've got function like this:
CREATE OR REPLACE
TYPE VARR_VARCHAR AS VARRAY(256) OF NVARCHAR2(500)
CREATE OR REPLACE
TYPE E_VARR_VARCHAR AS VARRAY(256) OF nVARCHAR2(4096)
FUNCTION find_id(
p_id IN VARCHAR2,
p_special_columns IN varr_varchar,
p_special_values IN e_varr_varchar,
RETURN VARCHAR2;How can I construct call to that function (nvarchar datatype is a need) using only pl/sql and can I do that with pure sql like select f() from dual; ?
I'm on 9.2.0.8 .
Regards
GregGselect find_id (p_id,VARR_VARCHAR('1','2','3'),e_varr_varchar('1','2','3')) from dual;
--sty. -
I have a script that does a nice check to see if two groups belong to admins group on each server.
It kind of works apart from , if there is a server is the list that in no longer in AD , it returns the results from the last server.
The code below will run ok , if a server is no longer in the domain the line that reads
...psbase.children.find(”Administrators”) will sometimes error with
Exception calling "Find" with "1" argument(s): "The network path was not found.
If I can some how test for this it would be ok but i tried to trap for string and for $null but i couldnt get it to work
so $result then writes its last entry again.
$Result = @()
$TestResult = @()
foreach($server in (gc c:\Input\ListOfComputers.txt)){
$computer = [ADSI](”WinNT://” + $server + “,computer”)
$Group = $computer.psbase.children.find(”Administrators”)
function getAdmins
{$members = ($Group.psbase.invoke(”Members”) | %{$_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null)}) -replace ('WinNT://d30.intra/' + $server + '/'), '' -replace ('WinNT://d30.intra/', 'd30.intra\') -replace ('WinNT://', '')
$members
$TestResult = ( getAdmins )
# Write-Host $TestResult.GetType().FullName
$Result += Write-Output "SERVER: $server"
$Result += Write-Output ' '
$Result += ( getAdmins )
if (-not ($TestResult -like '*/svc_Maneng'))
$Result += ' svc_Maneng Missing'
if (-not ($TestResult -like '*/m_DECO_COG_DPEMEA_admins'))
$Result += ' m_DECO_COG_DPEMEA_admins is Missing'
$Result += Write-Output '____________________________'
$Result += Write-Output ' '
$Result > c:\Output\output2.txt
Invoke-Item c:\Output\output2.txtHi Chen, thanks for your help- i may use that in a future program ;-)
I have now changed the code and got it working, i have posted if anyone else wants to use it.
$Result = @()
$TestResult = @()
foreach($server in (gc c:\Input\ListOfComputers.txt)){
$computer = [ADSI](”WinNT://” + $server + “,computer”)
if ($computer.name -eq $server){
$Group = $computer.psbase.children.find(”Administrators”)
function getAdmins
{$members = ($Group.psbase.invoke(”Members”) | %{$_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null)}) -replace ('WinNT://d30.intra/' + $server + '/'), '' -replace ('WinNT://d30.intra/', 'd30.intra\') -replace ('WinNT://', '')
$members
$TestResult = ( getAdmins )
# Write-Host $TestResult.GetType().FullName
$Result += Write-Output "SERVER: $server"
$Result += Write-Output ' '
$Result += ( getAdmins )
if (-not ($TestResult -like '*/svc_Maneng'))
$Result += ' svc_Maneng Missing'
if (-not ($TestResult -like '*/m_DECO_COG_DPEMEA_admins'))
$Result += ' m_DECO_COG_DPEMEA_admins is Missing'
$Result += Write-Output '____________________________'
$Result += Write-Output ' '
else
$Result += Write-Output '____________________________'
$Result += Write-Output ' '
$Result += Write-Output "************************************$server NETWORK NOT FOUND "
$Result += Write-Output '____________________________'
$Result += Write-Output ' '
$Result
$Result > c:\Output\output2.txt
Invoke-Item c:\Output\output2.txt -
Hi All,
I am getting error while executing oDATA service from SAP Netweaver Gateway
Error details:
RFC call ended with "Communication Failure" exception (Function call failed; could not find the function
I am using SAP NG 740
Project is created in Gateway system using SEGW having Map to Datasource option used.
in SPRO manage alias, I had seleted Local App option. Screen attached
I had tried all troubleshooting like delete and add service and alias in "/IWFND_MAINT_SERVICE".
but still getting same error for all service.
Kindly advise.
Regards
VivekHello Vivek,
Service builder would have also generated code for RFC Exception handling to catch exceptions raised when communication fails between your GW and BE for some reasons.
Handling is done for 1. System Failure 2. Communication Failure & 3. Business Failure;
Put a BP in your DPC or DP_EXT class where exception code is written to check what exactly is has caused communication failure.
Check if that RFC is existing in that destination or not.
For your reference : Code would be something like this. Put BP here and check the problem.
* Error and exception handling
IF lv_subrc <> 0.
* Execute the RFC exception handling process
me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling(
EXPORTING
iv_subrc = lv_subrc
iv_exp_message_text = lv_exc_msg ).
ENDIF.
Go inside this method and check to get info on what has to be done to resolve issue.
Check carefully what has gone wrong and fix it accordingly.
No need of adding service & deleting as problem is not because of that.
Regards,
Ashwin -
Today, I received this error when I re-added two email accounts that are tied in to my domain. The error is: "Terminating app due to uncaught exception 'MFSQLiteException', reason: 'inserting mailbox url' abort() called terminating with uncaught exception of type NSException"
Two days ago, at my wits end with email issues, I googled how to Reset Mail.app and followed the recommendation found here: https://discussions.apple.com/thread/2266399?tstart=0
That's. all. I've. done.
What should I do correct the error I'm receiving when adding my email accounts?Launch the Console application in any of the following ways:
☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
☞ Open LaunchPad. Click Utilities, then Console in the icon grid.
Step 1
For this step, the title of the Console window should be All Messages. If it isn't, select
SYSTEM LOG QUERIES ▹ All Messages
from the log list on the left. If you don't see that list, select
View ▹ Show Log List
from the menu bar at the top of the screen.
In the top right corner of the Console window, there's a search box labeled Filter. Initially the words "String Matching" are shown in that box. Enter the name of the crashed application or process. For example, if iTunes crashed, you would enter "iTunes" (without the quotes.)
Each message in the log begins with the date and time when it was entered. Select the messages from the time of the last crash, if any. Copy them to the Clipboard by pressing the key combination command-C. Paste into a reply to this message by pressing command-V.
☞ The log contains a vast amount of information, almost all of which is irrelevant to solving any particular problem. When posting a log extract, be selective. A few dozen lines are almost always more than enough.
Please don't indiscriminately dump thousands of lines from the log into this discussion.
Please don't post screenshots of log messages—post the text.
☞ Some private information, such as your name, may appear in the log. Anonymize before posting.
Step 2
In the Console window, select
DIAGNOSTIC AND USAGE INFORMATION ▹ User Diagnostic Reports
(not Diagnostic and Usage Messages) from the log list on the left. There is a disclosure triangle to the left of the list item. If the triangle is pointing to the right, click it so that it points down. You'll see a list of crash reports. The name of each report starts with the name of the process, and ends with ".crash". Select the most recent report related to the process in question. The contents of the report will appear on the right. Use copy and paste to post the entire contents—the text, not a screenshot.
I know the report is long, maybe several hundred lines. Please post all of it anyway.
If you don't see any reports listed, but you know there was a crash, you may have chosen Diagnostic and Usage Messages from the log list. Choose DIAGNOSTIC AND USAGE INFORMATION instead.
In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.)
Please don’t post other kinds of diagnostic report—they're very long and rarely helpful. -
SFTP adapter error : Catching exception calling messaging system
Error: com.aedaptive.sftp.adapter.SFTPException : Not all messages were delivered succesfully
Could not deliver message to XI: com.sap.aii.af.lib.mp.module.ModuleException: senderChannel 'ca09269447583427adc545f8c23d244b': Catching exception calling messaging system
This is error message which i get in sender communication channel while working with SFTP adapter.Hi Pooja,
I think it would be better to add getcause() to get the cause of the issue.
Ref: http://help.sap.com/javadocs/pi/SP3/xpi/com/sap/aii/af/lib/mp/module/ModuleException.html
Thanks, -
Finally cause Exception be forgotten
In trying out that finally cause previous return value be forgotten, as described on page 206 of "The Java Programming Language, 3rd edition", I wrote the following code, and tested it with jdk1.3.1. To my supprise, not only the return value was forgotten, the exception was appeared forgotten as well:
class PException extends Exception {
class Final {
void f1(int i) {
int result;
System.out.println("f1("+i+")");
try {
result = f2(i);
System.out.println("result = " + result);
} catch(Exception e) {
System.out.println("caught an Exception: " + e);
try {
result = f3(i);
System.out.println("result = " + result);
} catch(Exception e) {
System.out.println("caught an Exception: " + e);
int f2(int i) throws PException {
try {
if (i == 1) {
System.out.println("generate exception");
throw new PException();
return 1;
} finally {
return 2;
int f3(int i) throws PException {
if (i == 1) {
System.out.println("generate exception");
throw new PException();
return 1;
public static void main(String[] args) {
Final f = new Final();
f.f1(1);
f.f1(2);
f.f1(1);
}Here is the result:
f1(1)
generate exception
result = 2
generate exception
caught an Exception: PException
f1(2)
result = 2
result = 1
f1(1)
generate exception
result = 2
generate exception
caught an Exception: PExceptionThe concern here is that when the
try {
finally {
}pattern is used, without the catch block, purelly for flow control purpose, a return statement in the finally block could be problematic. If a finally block ends with a return statement, any exception that might be thrown in the try block would be ignored. The unhandled exception will not propergate, it simply lost in the midst. Because any code could throw unchecked exception, if the exception cannot afford to be lost, then one should be careful not to use return in the finally block. See the following test code:
class Finally {
void test() {
int result;
System.out.println("test()");
try {
result = f1();
System.out.println("result = " + result);
} catch(Exception e) {
System.out.println("Caught an Exception: " + e);
try {
result = f2();
System.out.println("result = " + result);
} catch(Exception e) {
System.out.println("Caught an Exception: " + e);
try {
f3();
} catch(Exception e) {
System.out.println("Caught an Exception: " + e);
try {
f4();
} catch(Exception e) {
System.out.println("Caught an Exception: " + e);
int f1() {
System.out.println("f1()");
int a = 0;
int b = 0;
try {
a = 1/0; // this generate an unchecked exception
b = 1;
} finally {
return b; // this return clobber the unchecked exception
int f2() {
System.out.println("f2()");
int a = 0;
int b = 0;
a = 1/0; // this generate an unchecked exception
b = 1;
return b;
void f3() {
System.out.println("f3()");
int a = 0;
int b = 0;
try {
a = 1/0; // this generate an unchecked exception
b = 1;
} finally {
return; // this return clobber the unchecked exception
void f4() {
System.out.println("f4()");
int a = 0;
int b = 0;
try {
a = 1/0; // this generate an unchecked exception
b = 1;
} finally {
public static void main(String[] args) {
Finally f = new Finally();
f.test();
/code]
Here are the results:test()
f1()
result = 0
f2()
Caught an Exception: java.lang.ArithmeticException: / by zero
f3()
f4()
Caught an Exception: java.lang.ArithmeticException: / by zero
We see that the devide by zero exception throw by f1() simply vanished, the unintended result 0, instead of the intended result 1, is returned. The test() method did not detect any abnormality in f1(), which is scary. To drive the point home, we try f3() and f4(), which has void return type. A simple return statement in f3() causes exception be lost. The stack frame seems intact, for otherwise, the test() method would exit abruptly before f2() even get a chance to be called.
Maybe you are looking for
-
HP Smart Web Printing (print is to small)
How can I make the font / text size bigger? When I print a web page it's so small I can't read it. I have a HP Photosmart C8180 all-in-one printer. Help Please :-(
-
My phone number is no longer linked to iMessage or FaceTime on my MacBook Pro.
I have tried to add my number to both iMessage and FaceTime but it will only allow an email address to be added. I checked my Apple ID and my phone number is there. I don't know why my phone number mysteriously disappeared, it had been linked since I
-
I need to buy a laptop for Sixth Form and I wish to buy a MacBook. I'm into design and programming and wish to continue these as my career. I currently have a 21.5" Late 2011 iMac as my main computer which I do all my work on but since I am going to
-
iTunes on my iPad has switched to Spanish somehow - any ideas how I reset it to English?
-
copied text attributes, animation, speed and font wont copy to another clip