English 中文(简体)
究竟是怎样才能在营地使用习俗例外类别?
原标题:What is the point of using custom exception class in php?

在一些图书馆,通常的做法是为每一种错误条件开设习俗例外课,例如:

class FileNotFound_Exception extends Exception {}

您可以处理某些类型的例外,但不能读到所有图书馆的所有来源代码,以记住每个例外类别,不能充分利用使用习俗例外。 大部分时间,我只是把他们赶上基础特殊类别:

catch (Exception $e)
{
    // log and display friendly error
}

Is there other ways to have benefit of custom Exception classes, without writing long list of catch blocks? I like Exceptions, but don t know how to use them properly. Thank you.

最佳回答

拥有自己的特殊类别的好处是,作为图书馆的作者,你可以追捕和处理。

try {
   if(somethingBadHappens) {
     throw MyCustomException( msg ,0)
   }
} catch (MyCustomException $e) {
  if(IcanHandleIt) {
    handleMyCustomException($e);
  } else {
    //InvalidArgumentException is used here as an example of  common  exception
    throw new InvalidArgumentException( I couldnt handle this! ,1,$e);
  }
}
问题回答

当然,习俗例外类别使你能够妥善处理错误。

如果是,

class Known_Exception extends Exception {}

以及像此那样的试捕组:

try {
    // something known to break
} catch (Known_Exception $e) {
    // handle known exception
} catch (Exception $e) {
    // Handle unknown exception
}

然后,你知道,例外的美元是一种未知的错误情况,可以据此处理,这对我非常有用。





相关问题
handling exceptions IN Action Filters

Is there a better way to handle exceptions that occur inside an Action Filter itself in ASP .NET MVC? There re 2 ways I can think of at the moment. Using a try catch and setting the HTTP Status ...

既可捕获,又可举出例外。

我有一种办法,可以进入亚洲开发银行,因此,我国的亚行在多瑙河航道中的所有 st子都位于一个试捕区。 它正在追捕Kexception

Cross compiler exception handling - Can it be done safely?

I am doing some maintenance on a C++ windows dll library that is required to work with different VC++ compilers (as I don’t want to address different mangling schemes). I have already eliminated any ...

File Handling Issue

I am developing a tool in c#, at one instance I start writing into a xml file continuously using my tool,when i suddenly restart my machine the particular xml file gets corrupted, what is the reason ...

Watch a memory location/install data breakpoint from code?

We have a memory overwrite problem. At some point, during the course of our program, a memory location is being overwritten and causing our program to crash. the problem happens only in release mode. ...

Unit Test for Exceptions Message

Is there a simple (Attribute-driven) way to have the following test fail on the message of the exception. [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void ExceptionTestTest() ...

热门标签