How to catch the "slice bounds out of range" error and write a handle for it - go

I read other questions about the "slice bounds of range" here in the stackoverflow, but none of them using the same context from this.
Then, none of the answers helped me.
In my use case, the "golang's syntax" of substring using [] doesn't return an error variable. It launches a runtime error using the "panic" instruction.
My goal is to avoid to reach on the "panic" instruction.
I need to treat this error and provide messages that describe with more details the context around the moment where this error had occurred.
Obs:
The content of the string variable which one I need to get the substring value is totally dynamic and the indexes that I have been using to get the substring value is equally calculated dynamically.

You need to do bounds checking on your indexes:
if j >= 0 && j <= len(str) {
y = str[:j]
}

Related

Assigning a variable the length of a string or array causes a "dynamic constant assignment" error in Ruby

I started working with Ruby today and looked up the appropriate syntax for basic operations. Apparently I wasn't careful enough because the lines calling length below throw the error "dynamic constant assignment". There may be even more mistakes waiting to be uncovered after this is fixed, but for now I will only focus on this error.
def isPalindrome(n)
m = n.to_s;
L = m.length; <-- error
for i in 0..L/2
if(m[i] != m[L-1-i])
return false;
end
end
return true;
end
def nthmax(n, a)
L = a.length; <-- error
if(n > L)
return nil;
end
a.sort;
return a[L-n];
end
Searching the error message leads to posts about how the error is thrown when someone tries to assign a constant a value that isn't actually constant. The question given here is not relevant because I'm not trying to make L a constant (this info was added to clarify that the question, at the time I asked it, was not a duplicate, nor is it a duplicate now).
Turns out that if the 1st letter of a variable is capitalized, it's treated as a constant. "L" should be changed to "l".
You stumbled over an unusual design aspect in Ruby language. Ruby does not have constants, but it calls identifiers that start with upper case latters as constants. You are allowed to modify them, but get a warning (not an error!) if you do this, as it happed in your assignment to L. If you really want to modify a constant without warning, you can do it with
# Don't do this unless you really have to!!!!
self.class.send(:remove_const, :L) # Make it disappear
L = new_value # Recreate it
It is considered bad practice (as you can already guess from the fact that remove_const is now a private method), and you do these tricks mostly if you go into Ruby meta-programming. In your case, I see no reason why you can't use a normal local variable instead.

Should i launch an error or correct the values

Suppose we create a list class with a function that eliminates elements from position a to position b.
The class is supposed to be used by other programmers (like std::list).
Example:
list values : {0,1,2,3,4,5,6} and we call this function with (begin = 2, end = 5).
This would change the list to being {0,1,6}
If the user calls the function with end > size of the list, it's better to just reassign end = size and delete until the last one or launch an exception like out_of_range?
This is a good question about programming standards. If someone calls your method with end > size, they have technically gone against the prerequisites of your function. It is possible the programmer called your function thinking it did something else, such as eliminated all list values in between the values they gave. If your function does not throw an exception, they will not know anything has gone wrong until there is a logical error later. The best practice if given incorrect parameters is to throw an exception, explaining what they did wrong. It puts more of a challenge on the person using your function, but it saves them more trouble later.
For input argument for rightIndex > list.size(), you have a few options to provide:
ERROR: Exception (Array index out of range)
WARNING: rightIndex is truncated to end of the list at Line 5:56
ASSERTION FAILED (Error): assert(rightIndex >= 0 && rightIndex < list.size());
Reference Mismatch Error: Reference provided by rightIndex is not matched with the function deleteBetween(leftIndex, rightIndex){ ... }
Segmentation Fault (SIGSEGV): Invalid memory reference and access violation, trying to read or write from/to a memory area that you have access to.

While loop throwing error at the start of while

I want to take the user's input of a positive integer where 1 < a < 10^6 and run a loop on it and then store it in a matrix which gets printed to the screen. However, my code is throwing a syntax error pointing to the letter "e" in while. Does anyone know why this error is appearing?
A = (while (a!=1)
If(rem(a,2)=0
floor(a^(1/2));
Else
floor(a^(3/2));
endwhile)
disp(A);
You're having several different problems in your code:
a while loop doesn't return anything, so you can't assign it to A
syntax is case sensitive, so it's if and else, not If and Else
you're missing a closing brace after the if clause
you're missing an endif
you're assigning to rem, use == to compare for equality

Go- Why Does My For Loop Throw "Unexpected Semi-colon or New-line"?

I'm writing a dice rolling function. In order to add the result of each die, I added to an output variable using a for loop. However, I'm getting an error thrown when I attempt to build;
syntax error: unexpected semicolon or newline, expecting {
This was thrown on the line initializing the for loop.
Here is my code:
for i := 0; i < [0]si; i++ {
output := output + mt.Intn([1]si)
}
si is simply an int array holding 2 values, and mt is the name I gave to math/rand when I imported it.
Your loop has several problems:
The use of square brackets is odd. Outside of type definitions, these go after slice/array names, e.g. x[i] would give you the ith element of the slice x.
There is no reference to i inside the loop body, and thus each iteration of the loop will do the same thing.
You should probably write output = output + ... without the colon. Otherwise, a new variable output is declared during each iteration of the loop, and forgotten immediately after so that the loop has no effect.
The compiler error is probably caused by the first of these problems.
You access an array with varname[idx] in Go, just like in most other languages. It's only when declaring a new array of type si that you use the [size]si prefix syntax. You're getting the error because your code is syntactically invalid. You're trying to compare i to an array of 0 si s.

VBScript: Finding the number of non-null elements in an array

What is the "best" way to determine the number of elements in an array in VBScript?
UBound() tells you how many slots have been allocated for the array, but not how many are filled--depending on the situation, those may or may not be the same numbers.
First off there is no predefined identifier called vbUndefined as the currently accepted answer appears to imply. That code only works when there is not an Option Explicit at the top of the script. If you are not yet using Option Explicit then start doing so, it will save you all manner of grief.
The value you could use in place of vbUndefined is Empty, e.g.,:-
If arr(x) = Empty Then ...
Empty is a predefined identify and is the default value of a variable or array element that has not yet had a value assigned to it.
However there is Gotcha to watch out for. The following statements all display true:-
MsgBox 0 = Empty
MsgBox "" = Empty
MsgBox CDate("30 Dec 1899") = True
Hence if you expect any of these values to be a valid defined value of an array element then comparing to Empty doesn't cut it.
If you really want to be sure that the element is truely "undefined" that is "empty" use the IsEmpty function:-
If IsEmpty(arr(x)) Then
IsEmpty will only return true if the parameter it actually properly Empty.
There is also another issue, Null is a possible value that can be held in an array or variable. However:-
MsgBox Null = Empty
Is a runtime error, "invalid use of null" and :-
MsgBox IsEmpty(Null)
is false. So you need to decide if Null means undefined or is a valid value. If Null also means undefined you need your If statement to look like:-
If IsEmpty(arr(x)) Or IsNull(arr(x)) Then ....
You might be able to waive this if you know a Null will never be assigned into the array.
I'm not aware of a non-iterative method to do this, so here's the iterative method:
Function countEmptySlots(arr)
Dim x, c
c = 0
For x = 0 To ubound(arr)
If arr(x) = vbUndefined Then c = c + 1
Next
countEmptySlots = c
End Function
As Spencer Ruport says, it's probably better to keep track yourself to begin with.
There's nothing built in to tell you what elements are filled. The best way is to keep track of this yourself using a count variable as you add/remove elements from the array.

Resources