0

Hi,

Is there a way to stop a function from returning a value if a condition evaluates to true.

For example my function returns the sum of two integers. How can I stop it from returning anything if one of the integers is negative

Class C1
{
  ...
 public int Sum(int a, int b)
 {
    if((a<0)||(b<0))
{ 
  trow new Exception();
}

else
{
return a+b;
}
}
}

I don't want my program to crash if a or b is negative, but I also don't want the function to return value

4
Contributors
12
Replies
14
Views
5 Years
Discussion Span
Last Post by c++_fem
Featured Replies
  • You can always use try-catch blocks to catch the exception. But in this cases of yours it seems not to need one. If your method has a return type, you have to return this type in any place in the Sum method. Otherwise the compiler will throw an error. You … Read More

  • If you only want to add a Exception then do it like: [CODE] public int Sum(int a, int b) { if ((a < 0) || (b < 0)) { throw new ArgumentException("Number cannot be negative"); } else { return a + b; } } [/CODE] Read More

  • This only depends of the structure of your code - where to catch exceptions. But ordinary we catch then on the place where they might occure. Read More

  • [QUOTE=Mitja Bonca;1674673]You can always use try-catch blocks to catch the exception. But in this cases of yours it seems not to need one. If your method has a return type, you have to return this type in any place in the Sum method. Otherwise the compiler will throw an error. … Read More

1

You can always use try-catch blocks to catch the exception. But in this cases of yours it seems not to need one.
If your method has a return type, you have to return this type in any place in the Sum method. Otherwise the compiler will throw an error.
You can do it:

private void YourMethod()
        {
            int a = -2;
            int b = 3;
            int c = Sum(a, b);
            if (c > 0)
            {
                //Ok!!
            }
            else
            {
                //show a message if needed
                //that some of values are negative
            }
        }

        public int Sum(int a, int b)
        {
            if (a < 0 || b < 0)
            {
                return 0;
            }
            else
            {
                return a + b;
            }
        }
0

Why won't you make the parameters unsigned integers?

You could do this, But if he was taking input from the user for example, he would have to do the same check for a negative value.

0

This was just a simple example.
I wanted to know how can I throw an exception so that my program continues on if something cannot be computed

I guess it shoud go something like this, but this doesn't work - after it displays the message the program crashes

Class Array
{
}

public int (Array a, Array b, int d)
{
  if((d>= a.Number_Of_Elements)||(d>b.Number_Of_Elements))
{
throw exception ("That element doesn't exist")
}
else
{
return a.element[d]+b.element[d]
}
}

Edited by c++_fem: n/a

1

If you only want to add a Exception then do it like:

public int Sum(int a, int b)
        {
            if ((a < 0) || (b < 0))
            {
                throw new ArgumentException("Number cannot be negative");
            }
            else
            {
                return a + b;
            }
        }
0

If you only want to add a Exception then do it like:

public int Sum(int a, int b)
        {
            if ((a < 0) || (b < 0))
            {
                throw new ArgumentException("Number cannot be negative");
            }
            else
            {
                return a + b;
            }
        }

This doesn't work, the program crashes after writing Number cannot be negative. Is there a way that the program could continue after writing this message?

Edited by c++_fem: n/a

0

I've also tried this :

public int (Array a, Array b, int d)
{
try
{
  if((d>= a.Number_Of_Elements)||(d>b.Number_Of_Elements))
{
throw new ArgumentException;
}
else
{
return a.element[d]+b.element[d]
}
}
catch(Exception e)
{
Console.Writeline("Out of range");
}
}

But it won't compile because "Not all code paths return a value"

Edited by c++_fem: n/a

0

I'm not sure, but you seem to want to do everything in one fell swoop. If d is >= number of elements, then just return an Integer like -1. Then you know, if the method returned -1, d was not a satisfactory number

0

I solved it.
I was should have been catching exceptions in main(), not in a specific method

1

This only depends of the structure of your code - where to catch exceptions. But ordinary we catch then on the place where they might occure.

1

You can always use try-catch blocks to catch the exception. But in this cases of yours it seems not to need one.
If your method has a return type, you have to return this type in any place in the Sum method. Otherwise the compiler will throw an error.
You can do it:

private void YourMethod()
        {
            int a = -2;
            int b = 3;
            int c = Sum(a, b);
            if (c > 0)
            {
                //Ok!!
            }
            else
            {
                //show a message if needed
                //that some of values are negative
            }
        }

        public int Sum(int a, int b)
        {
            if (a < 0 || b < 0)
            {
                return 0;
            }
            else
            {
                return a + b;
            }
        }

Just a quick question. What happens to your logic when both numbers(a and b) are zero?

Here's what I was suggesting when I mentioned using unsigned integers for parameters

using System;

namespace testit
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			UInt64 x = 0, y = 0;
			bool loop = true;
			
			while (loop)
			{
				try
				{
					Console.Write("Enter value a->");
					x = UInt64.Parse(Console.ReadLine());
					Console.Write("Enter value b->");
					y = UInt64.Parse(Console.ReadLine());
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
					continue;
				}
				loop = false;
			}
			
			Console.WriteLine(sum_them(x, y));
		}
		
		public static UInt64 sum_them(UInt64 a, UInt64 b)
		{
			return a + b;
		}
	}
}

Edited by gerard4143: n/a

0

Just a quick question. What happens to your logic when both numbers(a and b) are zero?

Here's what I was suggesting when I mentioned using unsigned integers for parameters

using System;

namespace testit
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			UInt64 x = 0, y = 0;
			bool loop = true;
			
			while (loop)
			{
				try
				{
					Console.Write("Enter value a->");
					x = UInt64.Parse(Console.ReadLine());
					Console.Write("Enter value b->");
					y = UInt64.Parse(Console.ReadLine());
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
					continue;
				}
				loop = false;
			}
			
			Console.WriteLine(sum_them(x, y));
		}
		
		public static UInt64 sum_them(UInt64 a, UInt64 b)
		{
			return a + b;
		}
	}
}

I didn't consider it.
Thanks to all of you

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.