\newcommand gives errors in math mode (with or without arguments)

Here is an alternative to your current situation - using an optional argument to specify the derivative order. This way you don't have to define a macro for "each" derivative:

\deriv[<order>]{<func>}{<var>}

Here's a minimal example:

enter image description here

\documentclass{article}
\newcommand{\deriv}[3][]{% \deriv[<order>]{<func>}{<var>}
  \ensuremath{\frac{\partial^{#1} {#2}}{\partial {#3}^{#1}}}}
\begin{document}
In text mode there is~\deriv{y}{x} and~\deriv[2]{y}{x}. In display mode there is
\[
  \deriv{y}{x}\ \textrm{and}\ \deriv[2]{y}{x}\rlap{.}
\]
\end{document}

The default <order> is empty, implying the first order partial derivative. If you want the default to be 2, modify the definition to read

\newcommand{\deriv}[3][2]{...}

Technically it is possible to use a macro with numbers in them, but the usage is much less intuitive than adding something like an optional argument (as given above). Here's an implementation that now allows you to use \nameuse{deriv2}{y}{x}:

\expandafter\def\csname deriv2\endcsname#1#2{%
  \ensuremath{\frac{\partial^2 {#1}}{\partial {#2}^2}}}
\makeatletter
\newcommand{\nameuse}[1]{\@nameuse{#1}}%
\makeatother

The optional argument beats this hands down.


you can fool TeX and use the 2 as a parameter:

\newcommand\deriv[3]{\ensuremath{\frac{\partial^2 {#2}}{\partial {#3}^2}}}

now you can use \deriv2{x}{y}. But that works only when there is no \deriv command


Since from 2019-07-21 there is a new package called derivative. It is very simple to use. Some very simple macros have been defined into this package.

enter image description here

\documentclass[a4paper,12pt]{article}
\usepackage{derivative}
\begin{document}
In text mode there is $\pdv{y}{x}, \quad \pdv[2]{y}{x}$. 
In display mode there is
\[\pdv{y}{x}, \quad \pdv[2]{y}{x}.\]
\end{document}

I have added a screenshot of page 7 to obtain the code of the your question.

enter image description here