Enforce each Inside method must have throw or enforce not use try catch block.
Below example InsideMethod2() is not implemted throw in this case when it's is calling in Main() method, should give some warning or error message saying that you must throw or should not use try catch block.
Example :
public void Main()
{
try
{
InsideMethod1();
InsideMethod2();
}
catch (System.Exception)
{
throw;
}
}
public int InsideMethod1()
{
try
{
// implementation here
}
catch (System.Exception)
{
// log
throw;
}
}
public int InsideMethod2()
{
// enforce throw or enforce not use try catch block
int a = 1, b = 0, c = 0;
try
{
c = a / b;
}
catch (System.Exception)
{
// enforce to throw
// log
}
return c;
}
Is it possible to enforce inside methods..?
Related
I should have a function that must return either a string of an error (through try / catch) or a different type T.
Example of such a function:
public T get()
{
T struttura;
try {
...
}
catch (Exception xcp) {
return xcp.Message;
}
...
return struttura;
}
There are ways to do this, but really consider if that's what you actually want. It is almost always better just to let the Exception bubble upwards into the calling code.
The first way is to use an out parameter.
public string get(out T result)
{
T struttura;
try{...}
catch (Exception xcp)
{
result = default(T);
return xcp.Message;
}
...
result = struttura;
return String.Empty;
}
The second way is to use a ValueTuple:
public (T, string) get()
{
T struttura;
try{...}
catch (Exception xcp){return (default(T), dexcp.Message);}
...
return (struttura, string.Empty);
}
The .net design guidelines https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing recommend never returning the exception as a return type. It’s always better design to throw the error and catch in the caller.
The guidelines also recommend that if you don’t want to throw the error that you can follow the TryParse pattern https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern. Typically you provide both methods, Get and TryGet. The presence of the Try method should indicate to callers that Get will throw exceptions but TryGet won’t. The TryGet also returns a Boolean if the operation was successful, allowing you to handle negative cases without using a try/catch block on the caller.
I suggest TryGet signature:
public bool TryGet(out T struttura) {
try {
...
struttura = ...
...
return true;
}
catch (Exception xcp){
struttura = default(T);
return false;
}
}
Usage:
if (TryGet(out var myStruct)) {
// succeeded, myStruct is returned struttura
}
else {
// failed
}
Or either do not catch exceptions at all or re-throw exception as custom one:
public T Get() {
try {
...
return struttura;
}
catch (Exception xcp) {
throw new MyException("My message", xcp);
}
}
Usage:
try {
myStruct = Get();
}
catch (MyException e) {
// Failed, e.Message for message
Console.WriteLine(e.Message);
}
Finally, you can mechanically combine value and message and return named tuple:
public (T value, string message) Get() {
try {
...
return (struttura, null);
}
catch (Exception xcp) {
return (default(T), xcp.message);
}
}
Usage:
var result = Get();
if (result.message == null) {
// succceded with result.value
}
else {
// failed with result.message
}
Is it possible to resume the execution of my Programm after the first catch even if i throwed the exception?
I made an example programm but the line where i added the exception to my List<string> has to be executed exactly after the inner and inside the outer foreach i know it would be possible if i wouldnt throw the exception but i have to do this aswell.
foreach(var x in x)
{
try
{
List<string> exs = new List<string>();
foreach(var a in b)
{
try
{
//...some code
}
catch(Exception ex)
{
throw ex;
}
finally
{
//...some code
}
}
exs.Add(ex);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
finally
{
//...some code
}
}
Don't throw them, but collect and print them later.
List<Exception> exs = new List<Exception>();
try
{
foreach(var a in b)
{
try
{
//...some code
}
catch(Exception ex)
{
exs.Add(ex);
}
finally
{
//...some code
}
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
//...some code
}
exs.ForEach(ex=> Console.WriteLine(ex.ToString()));
This is a MVCE of my problem.
I have this method using MSScriptControl to dynamically evaluate some formula.
public void DoCalculate()
{
try
{
var evaluator = new Evaluator();
IScriptControl ctrl = new ScriptControl();
ctrl.Language = "JavaScript";
ctrl.AddObject("Evaluator", evaluator, false);
var calcFunction = "Number(Evaluator.Divide(4,0))";
double rs = ctrl.Eval(calcFunction);
}
catch (CustomException cex)
{
// Handle CustomException.
}
catch (Exception ex)
{
// Handle general Exception.
}
}
This is the Evaluator class.
public class Evaluator
{
public double Divide(int a, int b)
{
if (b == 0)
{
throw new CustomException("Cannot divide by zero");
}
else
{
return a / b;
}
}
public void TestThrow()
{
throw new CustomException("This is a test");
}
}
And this is the CustomException class:
using System;
namespace Library
{
public class CustomException : Exception
{
public CustomException()
: base()
{
}
public CustomException(string message)
: base(message)
{
}
}
}
I expected that in this case a CustomException will be throw, and the first catch clause will be entered. However, I got an general Exception (I verified the exception type using GetType().Name) with the message "Cannot divide by zero" instead.
I did get the following error in Evaluator class though:
An exception of type 'Library.CustomException' occurred in XXX.dll but was not handled in user code
If I modify my DoCalculate() like this then I can catch a CustomException just fine:
public void DoCalculate()
{
try
{
var evaluator = new Evaluator();
evaluator.TestThrow();
}
catch (CustomException cex)
{
// Handle CustomException.
}
catch (Exception ex)
{
// Handle general Exception.
}
}
Does that mean it is impossible to define and throw my own exception from inside Eval function?
I'm using .NET 4.6.2 and Interop.MSScriptControl 1.0.0.0
This is the summary of the answer given in this link
COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT. So in order to throw proper exception, Let me suggest the following.
var evaluator = new Evaluator();
IScriptControl ctrl = new MSScriptControl.ScriptControl { Language = "VBScript" };
ctrl.AddObject("Evaluator", new Evaluator(), true);
const string calcFunction = "Evaluator.Divide(4,0)";
try {
double rs = ctrl.Eval(calcFunction);
}
catch (DivideByZeroException ex) {//Actual DivideByZeroException from .Net
//How can you divide by zero?!?!
}
catch (Exception ex) {
//STUFF
}
public class Evaluator {
public double Divide(int a, int b) {
if (b == 0) {
throw new MyDivideByZeroException();
}
return a / b;
}
}
public class MyDivideByZeroException : Exception {
public MyDivideByZeroException() {
HResult = -2147352558;
}
}
Can we write any code statement inside a Catch block of try catch in c#,
Or is there any restriction on what we cannot or should not write inside Catch block of C#?
You can't yield or await inside a catch block. So the following two won't compile:
public IEnumerable<int> SomeSequence()
{
try
{
//do something
}
catch
{
yield 1; //error
}
}
or
public async int SomeFuncAsync()
{
try
{
//do something
}
catch
{
await Task.Delay(1000); //error
}
}
You can easily work around this though:
public async int SomeFuncAsync()
{
Exception ex = null;
try
{
//do something
}
catch(Exception exc)
{
ex = exc;
}
if(ex != null) await Task.Delay(1000); // no error
}
I have a class which contains several methods.
One of the methods runs in a while loop (MainMethod).
I call out to helper methods in the same class from MainMethod.
The Try Catch is contained within MainMethod where most of the execution occurs.
If an exception occurs in a helper method which doesn't contain a Try Catch, will it be caught further up? i.e. inside MainMethod which called the helper method.
class Class1
{
public MainMethod()
{
while (true)
{
try
{
// ...
// ...
// ...
HelperMethod();
// ...
// ...
}
catch (Exception e)
{
// Console.WriteLine(e.ToString());
// logger.log(e.ToString();
// throw e;
// ...
}
}
}
public HelperMethod()
{
// No Try Catch
// if (today == "tuesday") program explodes.
}
}
Thanks.
Yes. If a method has no try/catch block it will "bubble up" the stack and be caught by the next handler up the chain. If there is no handler, that's when your program terminates because an exception was "unhandled".
Yes it will. Something like this:
public class Helper
{
public void SomeMethod()
{
throw new InvalidCastException("I don't like this cast.");
}
public void SomeOtherMethod()
{
throw new ArgumentException("Your argument is invalid.");
}
}
public class Caller
{
public void CallHelper()
{
try
{
new Helper().SomeMethod();
}
catch (ArgumentException exception)
{
// Do something there
}
catch (Exception exception)
{
// Do something here
}
try
{
new Helper().SomeOtherMethod();
}
catch (ArgumentException exception)
{
// Do something there
}
catch (Exception exception)
{
// Do something here
}
}
}
Note that if caller application handles that specific type of exception, specific catch block will be called.
IMHO, it is good to handle specific exceptions that may be thrown by methods you call from your code. However, that also means that author of method you are calling created a decent document sharing exceptions that we need to expect from his code.