Skip to content

Commit

Permalink
Add explanatory error message for VariableNotOwned errors (#3520)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Sep 20, 2023
1 parent 6a54e0c commit 1cd82da
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/variables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,41 @@ struct VariableNotOwned{V<:AbstractVariableRef} <: Exception
variable::V
end

function Base.showerror(io::IO, err::VariableNotOwned)
return print(
io,
"""
$err: the variable $(err.variable) cannot be used in this model because
it belongs to a different model.
## Explanation
Each variable belongs to a particular model. You cannot use a variable
inside a model to which it does not belong. For example:
```julia
model = Model()
@variable(model, x >= 0)
model2 = Model()
@objective(model2, Min, x) # Errors because x belongs to `model`
```
One common cause of this error is working with a main problem and a
subproblem.
```julia
model = Model()
@variable(model, x, Bin)
subproblem = Model()
@variable(subproblem, 0 <= x <= 1)
# The Julia binding `x` now refers to `subproblem[:x]`, not `model[:x]`
@objective(model, Min, x) # Errors because x belongs to `subproblem`
# do instead
@objective(model, Min, model[:x])
```""",
)
end

"""
check_belongs_to_model(func::AbstractJuMPScalar, model::AbstractModel)
Expand Down
9 changes: 9 additions & 0 deletions test/test_model.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1207,4 +1207,13 @@ function test_bridges_add_remove_coefficient_type()
return
end

function test_show_variable_not_owned()
model = Model()
@variable(model, x)
err = VariableNotOwned(x)
contents = sprint(showerror, err)
@test occursin("## Explanation", contents)
return
end

end # module TestModels

0 comments on commit 1cd82da

Please sign in to comment.