Search code examples
exceptiond

Alternative to catch in D?


I am watching Three Cool Things About D - The Case for the D Programing Language and it basically says dont use try/catch/finally (about the 38mark. 39:30 says you dont want to look at the try/catch it generates), its much nicer to use scope(failure) (theres also exit and success).

My question is what happens when you want to check the exception and do an action based on the exception such as alert the user the disk has no space or mark a url as 404 (.NET webclient/webrequest throws on this) or retry later if a 500 error code occurs. How would i do this? must i use try/catch or is there another way?


Solution

  • scope statements allow you to run code when exiting the scope that you declare them in. scope(success) runs when exiting the scope normally. scope(failure) runs when exiting the scope due to an exception being thrown. scope(exit) runs when exiting the scope regardless of how you exit the scope. None of them give you access to any exceptions being thrown. They just allow you to run code when exiting the current scope based on how you exit that scope.

    So, essentially, in cases where you would catch an exception, do something, and then throw it again without caring what the exception actually was, scope(failure) can be used instead of catch, and scope(exit) can be used instead of finally. However, if you actually need the exception, then you're going to have to catch it using a try-catch block. scope simply doesn't give you access to the exception, so you can't use a scope statement if you want to actually do something with an exception which was thrown. However, scope works great when you don't care what the exception actually was.