标签: throw

C++中的内联throw()方法

我试图定义一个非常简单的异常类.因为它很简单,我只想把它保存在.h文件中,但是编译器并不喜欢throw().代码:

#include <exception>
#include <string>

class PricingException : public virtual std::exception
{
private:
    std::string msg;
public:
        PricingException(std::string message) : msg(message) {}
        const char* what() const throw() { return msg.c_str(); }
        ~PricingException() throw() {}
};
Run Code Online (Sandbox Code Playgroud)

GCC给出以下错误:

/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:13: error: expected unqualified-id before ‘{’ token
/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: expected unqualified-id before ‘{’ token
Run Code Online (Sandbox Code Playgroud)

用于线throw().知道怎么解决吗?

编辑

我试图删除有问题的方法的主体,即

virtual ~PricingException() throw();// {}
Run Code Online (Sandbox Code Playgroud)

现在我得到更奇怪的错误信息:

/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: looser throw specifier for ‘virtual PricingException::~PricingException()’
/usr/include/c++/4.5/exception:65: error:   overriding ‘virtual std::exception::~exception() throw ()’
Run Code Online (Sandbox Code Playgroud)

它只是忽略了我的throw说明符!

c++ gcc throw

6
推荐指数
1
解决办法
2996
查看次数

object.ReferenceEquals或==运算符?

为什么ThrowIfNull实施为:

    static void ThrowIfNull<T>(this T argument, string name) where T : class
    {
        if (argument == null)
        {
            throw new ArgumentNullException(name);
        }
    }
Run Code Online (Sandbox Code Playgroud)

不会更好地重写为:

    static void ThrowIfNull<T>(this T argument, string name) where T : class
    {
        if (object.ReferenceEquals(argument, null))
        {
            throw new ArgumentNullException(name);
        }
    }
Run Code Online (Sandbox Code Playgroud)

优点:它有助于避免混淆Equals过载,并可能使代码更清晰.

对此有何不妥?应该有一些.

c# linq equals throw

6
推荐指数
2
解决办法
3280
查看次数

如何抛出,试试{} catch {}应该在现实世界中使用?

我的意思是,我知道关于throw的所有语言规则,尝试{} catch {},但我不确定我是否在现实世界中正确使用它们.请参阅以下示例:

我们有大量的科学代码可以完成各种图像处理工作,最近我们决定对其进行修改,使其更加强大.经常使用的一个例程是void rotate_in_place(float*image,image_size sz) ;

为了使其更加健壮,我们在代码的开头添加了一些健全性检查:

void rotate_in_place(float* image, image_size sz) {
    // rotate_in_place does not support non-square image;
    if (sz.nx != sz.ny)  throw NonSquareImageError;
    // rotate_in_place does not support image too small or too large
    if (sz.nx <= 2 || sz.nx > 1024)  throw WrongImageSizeError;
    // Real rode here
    .....
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是rotate_in_place()在1000多个地方使用,我应该用try {} catch {}包装每次调用rotate_in_place(),这对我来说会让代码难以置信地膨胀.另一种可能性是不包装任何try {} catch {}并让程序退出,但这与仅使用有什么不同

if (sz.nx != sz.ny) {
    cerr << "Error: non-squared image error!\n";
    exit(0);
}
Run Code Online (Sandbox Code Playgroud)

简而言之,我不太确定使用throw,try,catch,任何好建议的真正好处?

c++ exception try-catch throw

6
推荐指数
2
解决办法
926
查看次数

什么时候应该宣布"投掷",什么时候不宣布?

我注意到,例如,这两个都在起作用:

public void func(int a) throws IllegalArgumentException {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}

public void func(int a) {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}
Run Code Online (Sandbox Code Playgroud)

这让我问:

什么时候我应该宣布throws anException,什么时候不宣布,然后扔掉它而不宣布它?

java exception try-catch throw

6
推荐指数
1
解决办法
486
查看次数

关于投掷助手的想法

为了减少冗余代码,我有一些throw辅助方法:

protected static X ThrowInvalidOperation(string operation, X a, X b) {
    throw new InvalidOperationException("Invalid operation: " + a.type.ToString() + " " + operation + " " + b.type.ToString());
}
Run Code Online (Sandbox Code Playgroud)

用法:

    public static X operator +(X a, X b) {
        if (...) {
            return new X(...);
        }
        return ThrowInvalidOperation("+", a, b);
    }
Run Code Online (Sandbox Code Playgroud)

问题:因为运算符+必须总是返回一个值,所以我通过ThrowInvalidOperation返回一个值并使用它来调用它来修复它returnThrowInvalidOperation("+", a, b);

有许多不满 - 一个是因为我不能从返回不同类型的方法中调用它.
我希望有一种方法可以将辅助函数标记为"始终抛出异常",因此编译器会停止跟踪返回值.

问:我有什么可能做到这一点?

c# exception-handling exception helper throw

6
推荐指数
1
解决办法
549
查看次数

在catch块中重新抛出异常

如果这些信息是否正确,任何人都可以确认我:

在C++中,在catch块中我们可以使用throw语句重新抛出异常,但抛出的异常应该与当前捕获的异常具有相同的类型.

c++ exception throw

6
推荐指数
2
解决办法
8437
查看次数

如何在单个抛出java docs标记中有多个异常?

我想在我的代码中添加一个JavaDoc.我需要在一次抛出中添加多个异常.当我在下面添加时,它只识别NullPointerException不是IllegalArgumentException.有什么方法可以在单个throw标签中提供多个异常,这样当我将鼠标放在方法上时它可以识别这两个异常吗?

@throws NullPointerException, IllegalArgumentException when invalid userId, timeout is passed
Run Code Online (Sandbox Code Playgroud)

或者我需要这样做?通过这个,我重复两次相同的评论.

@throws NullPointerException when invalid userId, timeout is passed
@throws IllegalArgumentException when invalid userId, timeout is passed
Run Code Online (Sandbox Code Playgroud)

java javadoc throw

6
推荐指数
1
解决办法
2418
查看次数

困惑于C++ Exception throw语句

我是C++的新手,很抱歉提出非常愚蠢的问题,但我对C++的异常处理机制中的throw语句感到困惑.

  • 在下面的代码中,为什么我们调用名称与类名匹配的函数?
  • 它是构造函数吗?
  • 它是否正在创建一个实例class Except

我不理解那里的语法.

class A
{
public:
  class Except{};
  void foo() { throw Except(); }
};

int main()
{
   A a;
   try
   {
     a.foo();    
   }
   catch(Except E)//exception handler
   {
     cout << "Catched exception" << endl;    
   }
}
Run Code Online (Sandbox Code Playgroud)

c++ syntax exception-handling exception throw

6
推荐指数
1
解决办法
214
查看次数

抛出表达式不适用于布尔表达式?

投掷表达式适用于这种情况:

string myStr;

public MyObj( string myStr ) =>
    this.myStr = myStr ?? throw new ArgumentNullException( "myStr" );
Run Code Online (Sandbox Code Playgroud)

但为什么不编译呢?

bool isRunning;

public void Run() =>
    isRunning = !isRunning || throw new InvalidOperationException( "Already running" );
Run Code Online (Sandbox Code Playgroud)

c# throw c#-7.0

6
推荐指数
1
解决办法
148
查看次数

NSKeyedUnarchiver decodeObjectForKey:]:无法解码类的对象

我有一个具有多个目标的应用程序(每个目标是另一个客户端作为具有不同名称,捆绑标识符等的单独应用程序).

我有方法:

fileprivate static func loadSessionFromKeychain() -> UserSession? {
    if let sessionData = KeychainWrapper.standard.data(forKey: UserSession.sessionDefaultsKey) {

        print("sessionData:")
        print(sessionData.debugDescription)
            if let session = NSKeyedUnarchiver.unarchiveObject(with: sessionData) as? UserSession {
                _current = session
                return session
            } else {
                print("ERROR: Could not parse UserSession from Keychain")
            }
        return nil
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

该行if let session = NSKeyedUnarchiver.unarchiveObject(with: sessionData) as? UserSession {抛出错误:

*由于未捕获的异常'NSInvalidUnarchiveOperationException'终止应用程序,原因:'* - [NSKeyedUnarchiver decodeObjectForKey:]:无法解码类(_test__MyApp.UserSession)对象的密钥(root); 该类可以在源代码中定义,也可以在未链接的库中定义

我试图抓住,do {} catch {}但它没有抓住并抛出相同的错误+ xCode说

catch'block无法访问,因为'do'block`中没有抛出错误

任何想法如何解决这一问题?

UserSessionSwift.swift

    import UIKit
    import SwiftKeychainWrapper

    class …
Run Code Online (Sandbox Code Playgroud)

xcode throw ios swift

6
推荐指数
1
解决办法
2369
查看次数

标签 统计

throw ×10

exception ×5

c++ ×4

c# ×3

exception-handling ×2

java ×2

try-catch ×2

c#-7.0 ×1

equals ×1

gcc ×1

helper ×1

ios ×1

javadoc ×1

linq ×1

swift ×1

syntax ×1

xcode ×1