Jump to content
php.lv forumi

try/catch vs if/else


Trac3 !!

Recommended Posts

Man jau liekas, ka php manuāli ļoti labs piemērs pielietojumam:

<?php
function inverse($x) {
   if (!$x) {
       throw new Exception('Division by zero.');
   }
   else return 1/$x;
}

try {
   echo inverse(5) . "\n";
   echo inverse(0) . "\n";
} catch (Exception $e) {
   echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

 

Pats vari veidot savus kļūdu paziņojumus...

Link to comment
Share on other sites

Savus kļūdu paziņojumus var veidot arī bez try/throw/catch.

 

Labums ir tajā, ka nevajag taisīt 100 if pārbaudes, dezorganizējot visu kodu, piemēram:

if ()
{
if ()
{
	if ()
	{
		...
	}
	else
	{
		error = 1
	}
}
else
{
	error = 2
}
}
else
{
error = 3
}

Tā vietā taisam pārskatāmu:

try
{
if ( )
{
	throw(1)
}
...

if ()
{
	throw(2)
}
}
catch
{
if ( 1 )
{
	error = 1
}
else if ( 2 )
{
	error = 2
}
}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...