MethodError

MethodError(f, args)

A method with the required type signature does not exist in the given generic function.

Examples

In the Julia programming language, the function MethodError(f, args) is used to handle cases where a method with the required type signature does not exist in the given generic function. It is an error type that is thrown when a function is called with arguments that don't match any of its defined methods.

julia> foo(x::Int) = x^2
foo (generic function with 1 method)

julia> foo("hello")
ERROR: MethodError: no method matching foo(::String)
Closest candidates are:
  foo(::Int64) at REPL[1]:1

Here are some examples of how MethodError can be encountered and handled:

  1. Calling a function with incorrect argument type:

    julia> bar(x::Float64) = x^2
    bar (generic function with 1 method)
    
    julia> bar("hello")
    ERROR: MethodError: no method matching bar(::String)
    Closest candidates are:
     bar(::Float64) at REPL[1]:1

    In this example, the function bar is defined to accept a Float64 argument, but it is called with a String argument, resulting in a MethodError.

  2. Handling MethodError with a fallback method:

    julia> baz(x::Int) = x^2
    baz (generic function with 1 method)
    
    julia> baz(x::Float64) = x/2
    baz (generic function with 2 methods)
    
    julia> baz("hello")
    ERROR: MethodError: no method matching baz(::String)
    Closest candidates are:
     baz(::Int64) at REPL[1]:1
     baz(::Float64) at REPL[1]:3

    In this case, the function baz has two methods, one for Int and another for Float64. When called with a String argument, it throws a MethodError and provides the closest matching candidates. This allows the user to handle the error by providing a new method that can handle the specific argument type.

Common mistake example:

julia> add(x, y) = x + y
add (generic function with 1 method)

julia> add(5)
ERROR: MethodError: no method matching add(::Int64)
Closest candidates are:
  add(::Any, ::Any) at REPL[1]:1

In this example, the function add is defined to accept two arguments, but it is called with only one argument. As a result, a MethodError is thrown. Ensure that the function is called with the correct number and type of arguments to avoid such errors.

See Also

ArgumentError, AssertionError, BoundsError, DivideError, DomainError, EOFError, error, ErrorException, InexactError, InitError, KeyError, LoadError, MethodError, OutOfMemoryError, OverflowError, ParseError, ReadOnlyMemoryError, showerror, StackOverflowError, SystemError, TypeError, UndefRefError, UndefVarError,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: