我确定我会为此感到沮丧...但我来自一个没有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
/ catch
blocks比仅仅是旧时尚变量验证更好?还是仅仅是"Java"方式?
我需要编写一个使用(单行if)语句的语法,但我需要在某种意义上嵌套它:
(表达式1)?
(如果表达式2抛出ArgumentException
则string.empty
其他expression2
):string.empty
所以基本上我需要弄清楚在c#中单行if if语句中使用try catch的语法(单行因为我需要在linq to sql select语句中使用它.)
单行if语句我的意思是使用三元运算符if语句而没有任何分号.
我有一个在单元格中有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) 我想将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)
它不显示结果
下面代码的问题是我从未看到我的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) 我在下面的代码中遇到了一些问题.我还在学习,我不知道如何修复它.
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) 我试图在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) 快速最佳实践问题(注意我不允许在此代码中使用任何智能指针).我的印象是,如果我传递指向函数的指针并发生异常情况,那么如果在被调用函数或首次分配内存的函数中从未删除内存,则内存会泄露.删除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) 如果我正在从配置文件中读取字符串,我将使用类似于下面的方法,以防正在读取的文件中出现字符串并产生异常.但是,如果我想对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) 我看到很多例子,但我无法理解,如何使用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)