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

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;
            }
        }

Why won't you make the parameters unsigned integers?

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.

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]
}
}

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;
            }
        }

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?

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"

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

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

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.

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;
		}
	}
}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.