473,785 Members | 2,798 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to trap for error on COM instantiation

The usual example shown for trapping for failure of COM instantiation
(Windows systems) is something like (see for example
http://at2.php.net/manual/en/class.com.php):

$word = new COM("word.appli cation") or
die("Unable to instantiate Word");

This is all well and good, but if you are using a command
line interface (CLI) version of PHP 5 then you might wish to
have a little more sophisticated error handling. Specifically,
I have a function that looks like so:

function getWinDir() {
$result = "";
$oScript = new COM("MSScriptCo ntrol.ScriptCon trol");
...
return $result;
}

How do I trap for a COM instantion error here? In particular,
if it errors, I want to return ":Error" so the calling function
can deal with it. I do not want the program to abort. Nothing
I've tried seems to work. For example, suppose I'm having a bad
spelling day and leave off the final l to ensure an error.
If I insert an @ in the line, it will suppress the error reporting
and the program will also halt. And PHP doesn't like me trying

$oScript = new COM("MSScriptCo ntrol.ScriptCon tro") or
($result = ":Error");

I've also tried using set_error_handl er and changing the
error level reporting with error_reporting and varying
$oldIni = ini_set("com.au toregister_verb ose", 0); // $oldIni is 1
none of which has produced any joy.

Whenever the @ is there, I get a silent failure and a full stop.
If it's missing it also stops with the following message:
Fatal error: Uncaught exception 'com_exception' with message
'Failed to create COM object `MSScriptContro l.ScriptContro' :
Invalid syntax' in C:\Testing\DirF ind.php:18
Thanks for any tips,
Csaba Gabor from Vienna

Jul 17 '05 #1
5 6383
NC
Csaba Gabor wrote:

I have a function that looks like so:

function getWinDir() {
$result = "";
$oScript = new COM("MSScriptCo ntrol.ScriptCon trol");
...
return $result;
}

How do I trap for a COM instantion error here?


In PHP 5, potentially fatal COM errors result in the COM
extension throwing instances of the class com_exception.
So your script needs to catch those exceptions:

function getWinDir() {
try {
$oScript = new COM("MSScriptCo ntrol.ScriptCon trol");
$oScript->call_a_method( );
$oScript->call_another_m ethod();
...
return $result;
} catch (com_exception $e) {
return array('errorCod e' => $e->getCode(),
'errorMessage' => $e->getMessage() ,
'errorFile' => $e->getFile(),
'errorLine' => $e->getLine());
}
}

Cheers,
NC

Jul 17 '05 #2
NC wrote:
In PHP 5, potentially fatal COM errors result in the COM
extension throwing instances of the class com_exception.
So your script needs to catch those exceptions:

function getWinDir() {
try {
...
} catch (com_exception $e) { .... }
}


NC,

thank you, Thank You, THANK YOU! This was a majorly
nice way to go into the weekend. I had seen the comment
about Exceptions in http://php.net/com but I never used this
try / catch construct in PHP before and glossed over it.
Thanks again for pointing it out.

I have a follow up question about try / catch in general.
Is there a way (this has nothing to do with COM) that I can
use this contruct to catch all errors in the same place?

Example: the following code strikes me as an inelegant
workaround. Really, I'm looking for a default catch_all.

$err = ":Error";
try {
... some code which might error in unknown ways ...
$err = ""
} catch (Exception $e) { // this line doesn't work (it's ignored)
// since we haven't defined Exception, we'll never wind up here
}
if ($err) { // hacky was of compensating
// evidently, there was an error
}

Thanks,
Csaba

Jul 17 '05 #3
NC
Csaba Gabor wrote:

I have a follow up question about try / catch in general.
Is there a way (this has nothing to do with COM) that I can
use this contruct to catch all errors in the same place?
Yes. You can throw your own exception and catch it later.
Example: the following code strikes me as an inelegant
workaround. Really, I'm looking for a default catch_all.

$err = ":Error";
try {
... some code which might error in unknown ways ...
$err = ""
} catch (Exception $e) { // this line doesn't work (it's ignored)
// since we haven't defined Exception, we'll never wind up here
}
if ($err) { // hacky was of compensating
// evidently, there was an error
}


This can be replaced with something like this:

try {
// ... some code which might error in unknown ways ...
if ($something_is_ wrong) {
$error_message = 'Error: Something is wrong...';
$error_code = 666;
throw new Exception($erro r_message, $error_code);
}
} catch (Exception $e) {
// Now you can catch your own exception just as you
// would be catching any other...
}

Cheers,
NC

Jul 17 '05 #4
I seem to have messed up on what I posted to you. Here is example code
that does what I was looking for - a generic catch all (or at least
catch most) error handler for PHP5. The point is that I did not want
to test for errors, nor throw exceptions. I just want to catch all
errors/exceptions that happen so I can deal with them gracefully.

<?
// see http://php.net/error_reporting
error_reporting (E_ALL);

// see http://php.net/set_error_handler
function myErrorHandler( $errno, $errstr, $errfile, $errline) {
// a fifth argument (context) is passed, whether defined or not
print "Standard error in line $errline:";
print "<br>\n$errstr\ n<br>";
}
set_error_handl er('myErrorHand ler');

// see http://php.net/exceptions
try {
$foo = 7 / 0; // execution resumes after a warning
$bar = new COM("speling.er ror"); // exception is thrown
// exception thrown above => line below not executed
print "<br>\nThir d line of the try";
} catch (Exception $e) { // generic exception handler
print "<br>\nThro wn exeption in line " . $e->getLine();
print "<br>\n" . $e->getMessage() . "\n<br>";
}
print "<br>\nEnd of routine";
?>

Csaba Gabor from Vienna

Jul 17 '05 #5
NC
Csaba Gabor wrote:

I just want to catch all errors/exceptions that happen
so I can deal with them gracefully.


Well, at this point, an error and an exception are different
beasts and must be handled differently. You can, however, try
combining two handlers into one:

function handleItAll ($arg1, $arg2=NULL, $arg3=NULL, $arg4=NULL) {
if (is_object($arg 1)) {
// exception thrown; handle it
}
if (is_numeric($ar g1)) {
// error triggered; handle it
}
}

set_error_handl er('handleItAll ');
set_exception_h andler('handleI tAll');

Cheers,
NC

Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8661
by: LineVoltageHalogen | last post by:
Greeting All, I have a stored proc that dynamically truncates all the tables in my databases. I use a cursor and some dynamic sql for this: ...... create cursor Loop through sysobjects and get all table names in my database. .... exec ('truncate table ' + @TableName)
2
1879
by: deko | last post by:
I use db.execute to run a delete query. I've also tried DoCmd.OpenQuery. Both work fine, but neither appears to allow me to trap an error if referential integrity is violated - in which case no changes are made to the table, but it would be nice to provide the user with a friendly message telling him he's doing something wrong. I've thought about doing a DCount, but that's too much overhead. Is it possible to trap an error when table...
3
9564
by: Timo | last post by:
In javascript code on MyPage.aspx, I set a hidden IFRAME's source url: myframe.location.href = 'someotherpage.aspx'; If the session has timed out, preventing someotherpage.aspx from being loaded into the IFRAME, where can that error condition be trapped? Thanks Timo
2
3611
by: JP SIngh | last post by:
We are using an ASP page to allow our users to update this Active Directory Information. Our testing show that for 90% of the users this works fine but for a small number of users it gives an error '80072020' Is there a way to display a more friendly error message rather than it saying error '80072020'
2
4600
by: AlastairHardwick | last post by:
Hi, Wonder if you can help? I have an Image Management Database which holds various information relating to Ghost Images and Testing. I am using a textbox with a hyperlink to display the path to a PDF file within a networked filesystem. To open the PDF I have used the Application.FollowHyperLink(PDFPath) property to enable users to view a PDF by clicking on a "View" command Button. I need to be able to trap the error if some dumb...
7
2420
by: Bob Darlington | last post by:
I'm using the following routine to call UpdateDiary() - below: Private Sub Form_BeforeUpdate(Cancel As Integer) On Error GoTo Form_BeforeUpdate_Error Call UpdateDiary(Me!TenantCounter, "sfTenantDetailsOther") Exit Sub Form_BeforeUpdate_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") " _ & "in procedure Form_BeforeUpdate in Line " & Erl & "."
1
1241
by: vishalgupta | last post by:
i have a defined a function which i when call displays the saveas dialog box. i have used the following code: Private Sub ClT() On Error GoTo Cancel CommonDialog1.InitDir = "C:\" CommonDialog1.ShowSave __________________ Cancel: End Sub
3
1941
by: Longworth2 | last post by:
Hi there, Is there a way to avoid hard-coding the error number 2501 when trapping a no data error? Does Microsoft have a "code" for this error number ? Thanks Karla
0
1249
by: =?Utf-8?B?UHVjY2E=?= | last post by:
Hi, My C# application trys to access directorycontext during Form loading. Try and Catch if there is an exception. I then output an error message and then "this.Close();" to exit the application. But, as my applicaiton closes, the MS dialog comes up asking to send Error Report to MS. I tried using ThreadException event code from: http://msdn2.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx But I'm...
0
938
by: Bill Feder | last post by:
Private Sub EMAIL_DblClick(CANCEL As Integer) On Error GoTo HandleErr If IsNull(Me!) Then MsgBox "Customer Does Not Have An E-Mail Address" DoCmd.GoToControl "EMAIL" Else DoCmd.SendObject , "", "", EMAIL, "", "", "", "", True, ""
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9481
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3655
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.