简体   繁体   English

如何逐行读取文本文件中的数据时,如何捕获并忽略或处理异常

[英]How do I catch and ignore or handle an exception while reading data from a text file line by line

I am reading a file line by line from text file and do some processing. 我正在从文本文件中逐行读取文件并进行一些处理。 The problem is that if some error occurs at some line. 问题是如果在某些行发生某些错误。 Then an exception is generated, what I want is that I want to ignore that error and move to the next line to read. 然后生成一个异常,我想要的是我想忽略该错误并移动到下一行来读取。 But if an exception is generated then I cant continue reading input lines. 但如果生成异常,那么我就无法继续读取输入行。 Please help. 请帮忙。

If I'm assuming what you're asking for correctly, here's a basic outline of what your code could look like: 如果我假设你正确要求的是什么,这里是你的代码看起来像什么的基本概述:

using (StreamReader reader = File.OpenText("Path\to\your\file"))
{
    string line = null;
    while ((line = reader.ReadLine()) != null)
    {
        try
        {
            ProcessLine(line);
        }
        catch { /* Ignore exceptions */ }
    }
}

It's generally not a good idea to blindly catch all exceptions, so if you can, you should filter the exceptions caught by your catch block to something more specific. 盲目捕获所有异常通常不是一个好主意,所以如果可以,你应该将catch块捕获的异常过滤为更具体的异常。

If you really want to "ignore" exceptions, you can do something like: 如果你真的想“忽略”异常,你可以这样做:

try
{
    foo(); // Something that may throw an exception
}
catch
{
}

See http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx for more info. 有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx

But usually, an exception means something bad happened, and you'll probably want to handle that somehow. 但通常,异常意味着发生了一些不好的事情,你可能想以某种方式处理它。

try
{
//put the statement throwing the exception here
}
catch
{
//will eat the exception
}
//execution will continue here

Difficult to understand what you want to achieve, but you probably are asking for something like this: 很难理解你想要达到的目标,但你可能会要求这样的东西:

while(condition)
{
    try {
        //process file line here
    }
    catch (Exception ex) {
        LogException(ex);
    }
}

Not a good design decision in my opinion, by the way. 顺便说一句,在我看来,这不是一个好的设计决定。 Avoid it if you can. 如果可以,请避免使用它。

You need: 你需要:

using System.IO;

to get this to work. 让这个工作。


You can try: 你可以试试:

try
{
    string path = ""; // You must add the path here. Else it won't work.
    string[] lines = File.ReadAllLines(path);
    foreach(string line in lines)
    {
        Console.WriteLine(line);
    }
} catch (Exception ex, IOException ioex) {
    // It's optional. You can remove "Exception ex, IOException ioex" if you want. You can delete the code below too.
    Console.WriteLine(ex.ToString());
    Console.WriteLine();
    Console.WriteLine(ioex.ToString());
} finally
{
    // in this "finally" section, you can place anything else. "finally" section isn't important, just shows that method has no exceptions.
    // you can add something else like: Console.WriteLine("Code has no exceptions. Great!");
}

Good for advanced notepads. 适合高级笔记本。


EDIT : If you don't like the previous solution, this one can help you. 编辑 :如果你不喜欢以前的解决方案,这个可以帮助你。

string path = ""; // Again, path.
string[] lines = File.ReadAllLines(path);
foreach(string line in lines)
{
    try
    {
        Console.WriteLine(line);
    } catch(Exception ex, IOException ioex)
    { /* exception */ }
}

----- or ----- - - - 要么 - - -

string path = Console.ReadLine();
int turns = 0;
int maxturns = (File.ReadAllLines(path)).Count();
while (turns < maxturns)
{
    try
    {
        Console.WriteLine(File.ReadLines(path).Skip(turns).Take(1).First());
    } catch (Exception ex, IOException ioex) { /* exception */ }
    turns++;
}

Use a try catch and log the error . 使用try catch并记录错误 Your code would look like this: 您的代码如下所示:

try
{
   //read lines here
}
catch(Exception ex)
{
   //log the exception but don't throw anything.
}

You may be tempted to do nothing in the catch, but you will likely regret it later. 你可能很想在捕获中做任何事情,但你可能会后悔。

Try catch article: 试试文章:

http://www.homeandlearn.co.uk/csharp/csharp_s5p6.html http://www.homeandlearn.co.uk/csharp/csharp_s5p6.html

You simply need to wrap your processing code in a try / catch block. 您只需将处理代码包装在try / catch块中即可。

 try
 {
     DoSomeProcessing(lineThatIreadFromFile);
 }
 catch
 {
    // Log or Ignore error here
 }

However, please note that typically, just swallowing exceptions is never a good idea. 但请注意,通常情况下,吞咽异常绝不是一个好主意。 You should either fail your program (if unrecoverable), or potentially log those somewhere so you can fix why your program is failing. 您应该使程序失败(如果不可恢复),或者可能将其记录在某处,以便您可以修复程序失败的原因。

This is not a good approach. 这不是一个好方法。 You should be proactive and catch specific exceptions you can recover from. 您应该主动并捕获可以从中恢复的特定异常。 Catch them as close to the place where they are thrown from. 抓住它们靠近它们被抛出的地方。 And let the rest of them bubble up and terminate the process. 让其余的人冒泡并终止这个过程。 By swallowing all exceptions you will get an illusion of robustness while in fact your code may be full of bugs. 通过吞下所有异常,您将获得稳健的幻觉,而实际上您的代码可能充满了错误。 There is simply no 'quick and dirty' approach to exception handling. 没有“快速和肮脏”的异常处理方法。 See this answer . 看到这个答案

Avoid handling errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in application code. 通过在应用程序代码中捕获非特定异常(例如System.Exception,System.SystemException等)来避免处理错误。 There are cases when handling errors in applications is acceptable, but such cases are rare. 有些情况下,处理应用程序中的错误是可以接受的,但这种情况很少见。

An application should not handle exceptions that can result in an unexpected or exploitable state. 应用程序不应处理可能导致意外或可利用状态的异常。 If you cannot predict all possible causes of an exception and ensure that malicious code cannot exploit the resulting application state, you should allow the application to terminate instead of handling the exception. 如果您无法预测异常的所有可能原因并确保恶意代码无法利用生成的应用程序状态,则应允许应用程序终止而不是处理异常。

Based on the very limited information you provide there are two things you can do: 根据您提供的非常有限的信息,您可以做两件事:

  • Enclose the offending line with an empty catch block. 用空捕获块包含违规行。 Wait for next maintainer to do bad things to you. 等待下一个维护者给你做坏事。

  • Understand why the exception is happening and modify the code such that the next maintainer understands why it is safe that you ignored a certain condition 理解异常发生的原因并修改代码,以便下一个维护者理解为什么忽略某个条件是安全的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM