与Java的InputMismatchException和IOException Handling等效的C++异常处理机制是什么


import java.util.Scanner;
import java.io.*;
import java.util.InputMismatchException;
/*: 
NAME: Integrated Solution
Create a C++ or Java program for accepting an integer (n) and generate following point series:
x: n integer points from 0 to (n-1)
y: y=x*x
Design an effective mechanism for plotting these with minimal or nil effort from the user.*/
public class Integrated_Solution
 {
  private static final String FILENAME = "122.py";
  public static void main (String[] args)
   {
    Scanner sc = new Scanner (System.in);
    int n = -1;
    boolean flag = false;
    System.out.println ("Enter value of n: ");
    while(flag==false)
     {
      try
       {
        n = sc.nextInt();               // Inputting range from user
        if (n >= 0)
         flag=true;
        else
         System.out.println("Enter a positive value.");
       }
      catch (InputMismatchException e) // Exception Handling For any mismatch types (float, string etc.)
       {
        System.out.println ("Enter a positive integer value. n");
        sc.nextLine();
       }
     }
    try
     {
      FileWriter fw = new FileWriter (FILENAME); // Create a new file with the given filename
      fw.write("from pylab import linspace, plot, stem, show, title, xlabel, ylabeln"+                     
               "n = " + n + "n" +
               "x = linspace (0, n - 1, n)n"+
               "figure (num = None, figsize = (16,8), dpi = 80, facecolor='w', edgecolor='k')n"
               "title ('Plot for graph $f(x) = x^2$')n" +
               "xlabel ('$x$')n" +
               "ylabel ('$x^2$')n" +
               "plot (x, x * x, 'b')n"+    
               "stem (x, x * x, linefmt = 'g-', markerfont= 'bo')n"+                                                       
               "show ()n");            
      fw.close();
     }
    catch (IOException e)
     {
      System.out.println("Could not write file !!" + e.getMessage());
     }
    try
     {
      Runtime.getRuntime().exec ("python " + FILENAME); // Execute the created python file 
     }
    catch (IOException e)
     {
      System.out.println("Could not execute script. Call to runtime failed. " + e.getMessage ());
     } 
    sc.close(); 
   }
 }

这是我的Java解决方案。但是,我也希望在C++程序中实现相同的异常处理机制。

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main ()
 {
  ofstream outputFile;
  outputFile.open("122.py");    
  cout << "Enter the value of n : ";
  int n;
  cin >> n;
  outputFile << "from pylab import linspace, plot, stem, show, title, xlabel, ylabel, figuren" <<                      
               "n = " << n << "n" <<
               "x = linspace (0, n - 1, n)n"<< 
               "figure (num = None, figsize = (16,8), dpi = 80, facecolor='w', edgecolor='k')n" <<
               "title ('Plot for graph $f(x) = x^2$')n" <<            
               "xlabel ('$x$')n" <<
               "ylabel ('$x^2$')n" <<
               "plot (x, x * x, 'b')n"<<   
               "stem (x, x * x, linefmt = 'g-', markerfont= 'bo')n" <<             
               "show ()n";
  outputFile.close();
  system ("python 122.py");
 }

以上是我的C++程序减去异常处理。我应该进行哪些更改才能获得与Java程序相同的安全感?

此外,任何关于改进我的 Java 或 C++ 代码的建议(即使它与每个问题的异常处理无关(也将不胜感激。提前谢谢。

您可以非常轻松地设置何时抛出哪些异常。最常见的情况是当std::istream::failbitistream::badbit(说实话std::ios::badbitstd::ios::failbit,它们是继承的(:

int main() {
  int n;
  std::cin.exceptions(std::istream::failbit | std::istream::badbit);
  try {
    std::cin >> n;
  } catch(istream::failure) {
    std::cout << "failed to read value" << std::endl;
  }
  return 0;
}

同样的事情也适用于std::ifstream因为它也在std::istream之后继承。

为了检查system()功能中的故障,我建议遵循适用于Windows的MSDN和适用于Linux,Mac和其他基于Unix/受启发的系统的POSIX。MSDN,POSIX - 正如您在此处看到的,行为因您使用的系统而异。

最新更新