Error in <TROOT::WriteTObject>: The current directory (Rint) is not associated with a file. The object (Graph) has not been written

Here is a new version of the reduced macro showing how to proceed.

int analyzer2()
{
   int n = 51;
   int n2 = 11;
   TTree * TreeM;
   TBranch * Ener;
   string file_name1 = "ExN02_";
   string file_name2 = "keV.root";
   int energy = 500;
   TFile * graphs = new TFile("graphs.root", "RECREATE");

   for(int j = 0; j<n2; j++) {
      int energy2 = energy - 50;
      string prim_energy = to_string(energy);

      int kin_ener_Bfield;
      int energy_arr[n];
      int counts[n];

      TGraph *grph = new TGraph(n,energy_arr,counts);
      grph->SetName(Form("Graph_number_%d",j));
      grph->SetTitle(Form("This is the Graph number %d",j));

      grph->GetYaxis()->SetTitle("Counts");
      grph->GetXaxis()->SetTitle("Kinetic Energy for B-field [keV]");
      grph->SetMarkerStyle(21);
      grph->SetMarkerColor(2);
      grph->SetMarkerSize(.5);
      graphs->cd();
      grph->Write();
      energy = energy + 10;

   }

   graphs->Close();

   return 0;
}

It gives:

$ root -l analyzer2.C  
root [0] 
Processing analyzer2.C...
(int) 0
root [1] .q
$ rootls -l graphs.root
TGraph  May 25 17:16 2021 Graph_number_0   "This is the Graph number 0"
TGraph  May 25 17:16 2021 Graph_number_1   "This is the Graph number 1"
TGraph  May 25 17:16 2021 Graph_number_10  "This is the Graph number 10"
TGraph  May 25 17:16 2021 Graph_number_2   "This is the Graph number 2"
TGraph  May 25 17:16 2021 Graph_number_3   "This is the Graph number 3"
TGraph  May 25 17:16 2021 Graph_number_4   "This is the Graph number 4"
TGraph  May 25 17:16 2021 Graph_number_5   "This is the Graph number 5"
TGraph  May 25 17:16 2021 Graph_number_6   "This is the Graph number 6"
TGraph  May 25 17:16 2021 Graph_number_7   "This is the Graph number 7"
TGraph  May 25 17:16 2021 Graph_number_8   "This is the Graph number 8"
TGraph  May 25 17:16 2021 Graph_number_9   "This is the Graph number 9"
$