标签: try-catch

捕获异常只是懒惰的错误检查?

我确定我会为此感到沮丧...但我来自一个没有try/ catch块的语言,而且我正在学习Java异常捕获,我很难看到它不是只是一个懒惰的验证版本.我见过几个例子:

String Box [] = {"Book", "Pen", "Pencil"};
while(i<4)
{
    try
    {
        System.out.println(Box[i]);     
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
        System.out.println("Subscript Problem " + e);
        i++;
    }
Run Code Online (Sandbox Code Playgroud)

和:

int y = 0;
int x = 1;
// try block to "SEE" if an exception occurs
try
{
    int z = x/y;
    System.out.println("after division");
} 
catch (ArithmeticException ae) 
{
    System.out.println(" attempt to divide by 0");
}
Run Code Online (Sandbox Code Playgroud)

这些显然是非常基本的例子......但IMO要么是捕捉错误的可怕例子,要么没有充分的理由去做.在示例一中,如果我们循环元素的数量,Box我们不需要检查越界索引.在示例二中,如果我们检查0的除数,我们不需要检查它ArithmeticException.

是否有一个很好的例子或理由为什么使用try/ catchblocks比仅仅是旧时尚变量验证更好?还是仅仅是"Java"方式?

java exception-handling try-catch

-1
推荐指数
1
解决办法
746
查看次数

尝试catch为单行if语句

我需要编写一个使用(单行if)语句的语法,但我需要在某种意义上嵌套它:

(表达式1)?

(如果表达式2抛出ArgumentExceptionstring.empty其他expression2):string.empty

所以基本上我需要弄清楚在c#中单行if if语句中使用try catch的语法(单行因为我需要在linq to sql select语句中使用它.)

单行if语句我的意思是使用三元运算符if语句而没有任何分号.

c# if-statement try-catch

-1
推荐指数
1
解决办法
6949
查看次数

@try @catch阻止在iOS 6上工作但在iOS 5上没有

我有一个在单元格中有2个子视图的tableview(带标签的小缩略图),如果没有任何内容可以加载(当只有第一个子视图有加载的图像和标题时)我想要隐藏第二个子视图.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuse = @"reuse";
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:[Utils buildNibNameFromPrefix:@"ContentTableViewCell"] owner:self options:nil] objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    cell.cellIndex = indexPath.row;

    NSUInteger selectedIndex = [Utils getIndexForContentTitle:[Utils getContentBookmark]];
    NSUInteger titleIndex = indexPath.row * self.noOfContentPerCell;
    NSUInteger cellIndex = NSNotFound;
    for (int i = 0; i < self.noOfContentPerCell; i++) {
        @try {
            if (titleIndex == selectedIndex) {
                cellIndex = i;
            }

            NSArray *content;
            if ([[NSUserDefaults standardUserDefaults] …
Run Code Online (Sandbox Code Playgroud)

iphone try-catch ipad ios

-1
推荐指数
1
解决办法
1062
查看次数

这个java代码有什么问题?

我想将txt文件中的整行存储到我设法做到的数组中但是当从数组中搜索时我似乎无法做到这一点.这是代码:

import java.io.*;
import java.util.*;

public class GrandFinal {


public void readFromFile()throws IOException {
    String[] grand = new String[200];
    Scanner search = new Scanner(System.in);
    String query;


    try
    {

        Scanner reader = new Scanner(new FileInputStream("NRLdata.txt"));

        int i = 0;
        while (reader.hasNext()){
            i++;
            grand[i] = reader.next();



        }

        System.out.println("Search for GrandFinal: ");
        query = search.next();
        for(int j = 0; j <grand.length; j++)
        {
            if(grand[i].equals(query)){
                System.out.println (grand[j]);
            }
        }

    reader.close();
    }catch (FileNotFoundException e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
          }
    }


}
Run Code Online (Sandbox Code Playgroud)

它不显示结果

java arrays try-catch fileinputstream

-1
推荐指数
1
解决办法
107
查看次数

尝试捕获永远不会进入catch块

下面代码的问题是我从未看到我的catch代码执行.如果我的id不存在,则显示空数据网格.出了什么问题?

private void btnSearch_Click(object sender, EventArgs e)
{
    try
    {
        this.Cursor = Cursors.WaitCursor;
        SqlConnectie vandaag = new SqlConnectie();
        vandaag.Connection();
        SqlDataAdapter sda = new SqlDataAdapter("select ID, VERSIE, SB, NAAM, M_DATUM, V_DATUM from RE1 where ID=" + tbRecept.Text, SqlConnectie.conn);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dgvTemp.DataSource = dt;
        SqlConnectie.conn.Close();
        this.Cursor = Cursors.Default;
    }

    catch
    {
        MessageBox.Show("ID doesn't exist");
    }
}
Run Code Online (Sandbox Code Playgroud)

sql try-catch

-1
推荐指数
1
解决办法
41
查看次数

如何使用C#中的方法存储变量?

我在下面的代码中遇到了一些问题.我还在学习,我不知道如何修复它.

1.我想要做的是创建一个方法(GetInt)来存储变量,就像我想要在第二个方法(GetTrack)中那样进入我的main方法.

2.-当无效输入时我无法获取GetInt方法循环,​​我猜测try/catch和boolean thingy有问题

谢谢

//Get int Method
static public void GetInt(string sPrompt, int iMin, int iMax)
{
    int iNum;
    bool bError = false;

    do
    {
        bError = true;
        try
        {
            Console.Write(sPrompt);
            iNum = int.Parse(Console.ReadLine());
            if ((iNum < iMin) || (iNum > iMax))
            {
                Console.WriteLine("The value is out of range.");
                bError = true;
            }
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An invalid number was entered, please try again.");
            bError = true;
        }
    }
    while (bError == false);
}

//Get Track Method
static …
Run Code Online (Sandbox Code Playgroud)

c# methods boolean try-catch do-while

-1
推荐指数
1
解决办法
85
查看次数

FileNotFound尝试在1,000,000英寸的文本文件中查找重击手

我试图在1,000,000英寸的文本文件中找到重击手.

出于某种原因,当我运行它时,永远不会找到该文件.

我不明白我做错了什么,所以任何帮助都是最好的.

我相信我的整个程序的代码是正确的,除了它找不到文件的事实.

public class HH1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int k = 100;
        int count = 0;
        ArrayList<Integer> intList = new ArrayList<Integer>();
        File file = null;
        Scanner s = null;

        try {
            file = new File("IT179ProjectData.txt");
            s = new Scanner(file);
        } catch (Exception e) {
            System.out.println("Error");
            System.exit(0);
        }

        //Taking values from text file and inserting into an array list 
        while (s.hasNext()) {
            intList.add(s.nextInt());

        } …
Run Code Online (Sandbox Code Playgroud)

java arrays file arraylist try-catch

-1
推荐指数
1
解决办法
60
查看次数

何时删除try-catch块中的指针

快速最佳实践问题(注意我不允许在此代码中使用任何智能指针).我的印象是,如果我传递指向函数的指针并发生异常情况,那么如果在被调用函数或首次分配内存的函数中从未删除内存,则内存会泄露.删除catch块中的内存是否安全,还是应该删除调用函数中的内存?

例:

int main() {
  object* myPtr = new object(); //dynamic memory on heap
  foo(*myPtr);  //pass pointer to function foo

  return 0;
}

void foo(object &pointer) {
  try {
    /* do stuff here
    with the pointer */
  }
  catch (const char &e) {
    cout<< "An error occured: " << e << endl;
  }
  catch (...)
    cout<< "Caught unknown exception." << endl;
  }
}
Run Code Online (Sandbox Code Playgroud)

函数返回后我应该删除指针吗?

 int main() {
      object* myPtr = new object(); //dynamic memory on heap
      foo(*myPtr);  //pass pointer to …
Run Code Online (Sandbox Code Playgroud)

c++ memory pointers try-catch

-1
推荐指数
1
解决办法
981
查看次数

Try-catch在C#中创建新数组 - 在哪里初始化它?

如果我正在从配置文件中读取字符串,我将使用类似于下面的方法,以防正在读取的文件中出现字符串并产生异常.但是,如果我想对string []数组做同样的事情,我不能在try块之外"新建"因为大小未知.

我不能在try块本身新建它.应该如何处理?

string[] logContent; // can't new it up here as don't know the size

                try
                {
                    logContent = File.ReadAllLines(aLogFile);
                }
                catch
                {
                    throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");
                }
Run Code Online (Sandbox Code Playgroud)

c# try-catch

-2
推荐指数
1
解决办法
499
查看次数

如何使用try catch与构造函数?

我看到很多例子,但我无法理解,如何使用try catch与一个简单的构造函数,我写了一个示例程序:

class A
 {
   public:
    try {
       A()
        { cout << "in costr\n"; throw 10;}
    }//try closed
   catch (int a)
{ cout << "caught 1 \n"; }

 };

main()
 {
   A *ptr = new A;
   }
Run Code Online (Sandbox Code Playgroud)
  1. 该程序给出了编译错误
  2. 如果发现异常,对象会发生什么?

c++ constructor try-catch

-2
推荐指数
3
解决办法
1万
查看次数