GVKun编程网logo

没有括号的“ raise exception()”和“ raise exception”之间有区别吗?(没有括号的话)

12

想了解没有括号的“raiseexception的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于”和“raiseexception”之间有区别吗?的相关问题,此外,我们还将为您介绍关于asp.

想了解没有括号的“ raise exception的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于”和“ raise exception”之间有区别吗?的相关问题,此外,我们还将为您介绍关于asp.net-mvc – HttpResponseException和HttpException之间有什么区别?、c# – ArgumentException和Exception之间有什么区别?、com.facebook.crypto.exception.KeyChainException的实例源码、except: 和 except Exception as e 之间的区别:的新知识。

本文目录一览:

没有括号的“ raise exception()”和“ raise exception”之间有区别吗?(没有括号的话)

没有括号的“ raise exception()”和“ raise exception”之间有区别吗?(没有括号的话)

定义无参数异常:

class MyException(Exception):    pass

举起时,它们之间是否有任何区别:

raise MyException

raise MyException()

我找不到任何东西。它仅仅是一个重载的语法吗?

答案1

小编典典

简短的回答是,无论raise MyExceptionraise MyException()做同样的事情。第一种形式会自动实例化您的异常。

docs的相关部分说:“ raise
将第一个表达式评估为异常对象。它必须是BaseException的子类或实例。如果是类,则在需要时通过使用实例化该类来获取异常实例。没有争论。”

也就是说,即使语义相同,第一种形式在微观上也更快,而第二种形式则更加灵活(因为如果需要,可以将其传递给参数)。

大多数人在Python中(即标准库,流行的应用程序和许多书中)使用的通常样式是在raiseMyException没有参数的情况下使用。人们仅在需要传递一些参数时才直接实例化异常。例如: raise KeyError(badkey)

asp.net-mvc – HttpResponseException和HttpException之间有什么区别?

asp.net-mvc – HttpResponseException和HttpException之间有什么区别?

从 http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

HttpResponseException

What happens if a Web API controller throws an exception? By default,
most exceptions are translated into an HTTP response with status code
500,Internal Server Error.

The HttpResponseException type is a special case. This exception
returns any HTTP status code that you specify in the constructor of
the exception.

除了它没有. fiddler向我显示一个500被退回.

但是,HttpException似乎做了那篇文章.

文件是错误的还是我错过了什么?

UPDATE

在打字时,我有一个想法.我试过两个控制器,一个ApiController和一个标准的MVC控制器.

这两个异常根据他们抛出的控制器的类型相互反向工作.

>使用HttpResponseException从API返回适当的HTTP代码
控制器.
>使用HttpException从一个返回一个适当的HTTP代码
MVC控制器.

解决方法

[将我的更新移至答案]

在打字时,一个ApiController和一个标准的MVC控制器.

这两个异常根据他们抛出的控制器的类型相互反向工作.

>使用HttpResponseException从API控制器返回适当的HTTP代码.>使用HttpException从MVC控制器返回适当的HTTP代码.

c# – ArgumentException和Exception之间有什么区别?

c# – ArgumentException和Exception之间有什么区别?

在我们教授的示例代码中,他有一个看起来像这样的片段:

if (name == null || name == "")
    throw new ArgumentException("name is null or empty");

另一个看起来像这样的片段:

if (!File.Exists(name))
{
    throw new Exception("File does not exist!");
}

我只是想知道不同之处是什么以及为什么一个在另一个之上使用

解决方法

Exception是所有异常的基类. ArgumentException用于表示参数无效.它是Exception的子类.使用catch,您实际上可以根据异常的类型进行过滤,并以不同的方式处理每个异常.

MSDN很好地描述了它:

When you have to throw an exception,you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. You should use a standard exception type under these two conditions:

  • You are throwing an exception that is caused by a usage error (that is,by an error in program logic made by the developer who is calling your method). Typically,you would throw an exception such as ArgumentException,ArgumentNullException,InvalidOperationException,or NotSupportedException. The string you supply to the exception object’s constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information,see the Message property.
  • You are handling an error that can be communicated to the caller with an existing .NET Framework exception. You should throw the most derived exception possible. For example,if a method requires an argument to be a valid member of an enumeration type,you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.

com.facebook.crypto.exception.KeyChainException的实例源码

com.facebook.crypto.exception.KeyChainException的实例源码

项目:Patrons    文件:ConcealStringSetPreference.java   
@Override public void set(final Set<String> value) {
  final Set<String> encryptedSet = new HashSet<>(value.size());
  for (final String s : value) {
    try {
      encryptedSet.add(Base64.encodetoString(
          crypto.encrypt(
              s.getBytes(Charset.defaultCharset()),entity
          ),Base64.NO_WRAP
      ));
    } catch (KeyChainException | CryptoInitializationException | IOException e) {
      Log.e(TAG,e.getMessage());
      encryptedSet.add(null);
    }
  }
  preferences.edit().putStringSet(key,encryptedSet).apply();
}
项目:Patrons    文件:ConcealStringPreference.java   
@Override public void set(final String value) {
  try {
    if (value != null) {
      super.set(Base64.encodetoString(
          crypto.encrypt(
              value.getBytes(Charset.defaultCharset()),Base64.NO_WRAP
      ));
    } else {
      delete();
    }
  } catch (KeyChainException | CryptoInitializationException | IOException e) {
    Log.e(TAG,e.getMessage());
  }
}
项目:encryptedprefs    文件:MemoryKeyChain.java   
@Override
public synchronized byte[] getCipherKey() throws KeyChainException {
    if (!setCipherKey) {
        PasswordBasedKeyDerivation derivation = new PasswordBasedKeyDerivation(secureRandom,nativeCryptoLibrary);
        derivation.setPassword(password);
        derivation.setSalt(password.getBytes());
        derivation.setIterations(IteraTION_COUNT);

        derivation.setKeyLengthInBytes(cryptoConfig.keyLength);

        try {
            cipherKey = derivation.generate();
        } catch (CryptoInitializationException e) {
            return null;
        }
    }
    setCipherKey = true;
    return cipherKey;
}
项目:secure-preferences    文件:SecurePreferences.java   
private String encrypt(final String plainText) {
    if (TextUtils.isEmpty(plainText)) {
        return plainText;
    }

    byte[] cipherText = null;

    if (!crypto.isAvailable()) {
        log(Log.WARN,"encrypt: crypto not available");
        return null;
    }

    try {
        cipherText = crypto.encrypt(plainText.getBytes(),entity);
    } catch (KeyChainException | CryptoInitializationException | IOException e) {
        log(Log.ERROR,"encrypt: " + e);
    }

    return cipherText != null ? Base64.encodetoString(cipherText,Base64.DEFAULT) : null;
}
项目:secure-preferences    文件:SecurePreferences.java   
private String decrypt(final String encryptedText) {
    if (TextUtils.isEmpty(encryptedText)) {
        return encryptedText;
    }

    byte[] plainText = null;

    if (!crypto.isAvailable()) {
        log(Log.WARN,"decrypt: crypto not available");
        return null;
    }

    try {
        plainText = crypto.decrypt(Base64.decode(encryptedText,Base64.DEFAULT),"decrypt: " + e);
    }

    return plainText != null
            ? new String(plainText)
            : null;
}
项目:LsPush    文件:BeeConcealKeyChain.java   
private byte[] maybeGenerateKey(String key,int length) throws KeyChainException,JAQException {
    byte[] data;
    String salt = mSharedPreferences.getString(CommonCrypto.hashPrefKey(key),"");
    if (!TextUtils.isEmpty(salt)) {
        try {
            data = BeeCrypto.get().decrypt(salt.getBytes(CharsetsSupport.UTF_8));
            data = Base64.decode(data,Base64.NO_WRAP);
        } catch (Exception e) {
            Timber.w(e,"get key from preferences failure");
            data = generateKeyAndSave(key,length);
        }
    } else {
        data = generateKeyAndSave(key,length);
    }

    return data;
}
项目:ConcealSharedPreference-Android    文件:ConcealCrypto.java   
@RequiresPermission(allOf = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE})
public File obscureFile(File file,boolean deleteOldFile){
    if (enableCrypto) {
        try {
            boolean isImage = FileUtils.isFileForImage(file);

            File mEncryptedFile = new File(makeDirectory()+DEFAULT_PREFIX_FILENAME+file.getName());
            OutputStream fileStream = new bufferedoutputstream(new FileOutputStream(mEncryptedFile));
            OutputStream outputStream = crypto.getCipherOutputStream(fileStream,mEntityPassword);

            int read;
            byte[] buffer = new byte[1024];
            BufferedInputStream  bis = new BufferedInputStream(new FileInputStream(file));
            while ((read = bis.read(buffer)) != -1) {
                outputStream.write(buffer,read);
            }
            outputStream.close();
            bis.close();

            if (deleteOldFile)
                file.delete();

            File pathDir = new File(isImage?makeImagesDirectory():makeFileDirectory());
            return FileUtils.moveFile(mEncryptedFile,pathDir);

        } catch (KeyChainException | CryptoInitializationException | IOException e) {
            e.printstacktrace();
            return null;
        }
    }
    else {
        return file;
    }
}
项目:encryptedprefs    文件:MemoryKeyChain.java   
@Override
public byte[] getMacKey() throws KeyChainException {
    if (!setMacKey) {
        macKey = new byte[NativeMac.KEY_LENGTH];
        secureRandom.nextBytes(macKey);
    }
    setMacKey = true;
    return macKey;
}
项目:LsPush    文件:BeeConcealKeyChain.java   
@Override
public byte[] getCipherKey() throws KeyChainException {
    if (mCipherKey == null) {
        try {
            mCipherKey = maybeGenerateKey(CIPHER_KEY,mCryptoConfig.keyLength);
        } catch (JAQException e) {
            Timber.w(e,"generate cipher key failure");
            throw new KeyChainException(e.getMessage(),e);
        }
    }
    return mCipherKey;
}
项目:LsPush    文件:BeeConcealKeyChain.java   
@Override
public byte[] getMacKey() throws KeyChainException {
    if (mMacKey == null) {
        try {
            mMacKey = maybeGenerateKey(MAC_KEY,64);
        } catch (JAQException e) {
            throw new KeyChainException(e.getMessage(),e);
        }
    }
    return mMacKey;
}
项目:LsPush    文件:PreferenceUtils.java   
private void put(String key,String hashKey,String value)
    throws KeyChainException,CryptoInitializationException,IOException {
    Entity entity = Entity.create(key); // original key
    byte[] data = mCrypto.encrypt(value.getBytes(CharsetsSupport.UTF_8),entity);

    mPreference.edit().putString(hashKey,Base64.encodetoString(data,Base64.NO_WRAP)).apply();
}
项目:DroidCon-Poland    文件:CryptoManager.java   
public Bitmap decryptPhoto(String filename) throws IOException,KeyChainException {
    FileInputStream fileStream = new FileInputStream(path + filename);
    InputStream inputStream = crypto.getCipherInputStream(fileStream,entity);
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    inputStream.close();
    return bitmap;
}
项目:droid-stealth    文件:ConcealCrypto.java   
/**
 * Encrypts the unencrypted file. Can throw a lot of errors
 *
 * @param encrypted
 * @param unencrypted
 * @param entityName
 * @throws IOException
 * @throws CryptoInitializationException
 * @throws KeyChainException
 */
@Override
public void encrypt(File encrypted,File unencrypted,String entityName) throws IOException,KeyChainException {
    doFileChecks(unencrypted,encrypted);

    FileInputStream from = new FileInputStream(unencrypted); // Stream to read from source
    OutputStream to = crypto.getCipherOutputStream(new FileOutputStream(encrypted),new Entity(entityName)); // Stream to write to destination

    copyStreams(from,to);
}
项目:droid-stealth    文件:ConcealCrypto.java   
/**
 * Decrypts the encrypted file. Can also throw a lot of errors
 *
 * @param encrypted
 * @param unencrypted
 * @param entityName
 * @throws IOException
 * @throws CryptoInitializationException
 * @throws KeyChainException
 */
@Override
public void decrypt(File encrypted,KeyChainException {
    doFileChecks(encrypted,unencrypted);

    InputStream from = crypto.getCipherInputStream(new FileInputStream(encrypted),new Entity(entityName));

    FileOutputStream to = new FileOutputStream(unencrypted);

    copyStreams(from,to);
}
项目:ConcealSharedPreference-Android    文件:ConcealCrypto.java   
@RequiresPermission(allOf = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE})
public File deObscureFile(File file,boolean deleteOldFile){
    if (enableCrypto) {
        try {
            if (file.getName().contains(DEFAULT_PREFIX_FILENAME)) {

                boolean isImage = FileUtils.isFileForImage(file);

                File mDecryptedFile = new File(makeDirectory() + file.getName().replace(DEFAULT_PREFIX_FILENAME,""));

                InputStream inputStream = crypto.getCipherInputStream(new FileInputStream(file),mEntityPassword);
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                OutputStream outputStream = new FileOutputStream(mDecryptedFile);
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                int mRead;
                byte[] mBuffer = new byte[1024];
                while ((mRead = bis.read(mBuffer)) != -1) {
                    outputStream.write(mBuffer,mRead);
                }
                bis.close();
                out.writeto(outputStream);
                inputStream.close();
                outputStream.close();
                out.close();

                if (deleteOldFile)
                    file.delete();

                File pathDir = new File(isImage?makeImagesDirectory():makeFileDirectory());
                return FileUtils.moveFile(mDecryptedFile,pathDir);
            }

            return null;

        } catch (KeyChainException | CryptoInitializationException | IOException e) {
            e.printstacktrace();
            return null;
        }
    }

    return file;
}
项目:encryptedprefs    文件:MemoryKeyChain.java   
@Override
public byte[] getNewIV() throws KeyChainException {
    byte[] iv = new byte[cryptoConfig.ivLength];
    secureRandom.nextBytes(iv);
    return iv;
}
项目:Sunazuri    文件:EncryptionUtils.java   
public static String encrypt(Crypto crypto,String alias,String plainText)
        throws IOException,KeyChainException,CryptoInitializationException {
    final byte[] bytes = crypto.encrypt(plainText.getBytes(ENCODING),Entity.create(alias));
    return Base64.encodetoString(bytes,BASE64_FLAG);
}
项目:Sunazuri    文件:EncryptionUtils.java   
public static String decrypt(Crypto crypto,String encryptedText)
        throws IOException,CryptoInitializationException {
    final byte[] bytes = crypto.decrypt(Base64.decode(encryptedText,BASE64_FLAG),Entity.create(alias));
    return new String(bytes,ENCODING);
}
项目:LsPush    文件:BeeConcealKeyChain.java   
@Override
public byte[] getNewIV() throws KeyChainException {
    byte[] iv = new byte[mCryptoConfig.ivLength];
    mSecureRandom.nextBytes(iv);
    return iv;
}
项目:DroidCon-Poland    文件:CryptoManager.java   
public void savePhotoEncrypted(Bitmap imageBitmap,String filename) throws KeyChainException,IOException {
    FileOutputStream fileStream = new FileOutputStream(path + filename);
    OutputStream outputStream = crypto.getCipherOutputStream(fileStream,entity);
    imageBitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
    outputStream.close();
}
项目:droid-stealth    文件:ICrypto.java   
/**
 * Encrypts a file input stream to the given file
 * @param encrypted file to be written to. Cannot be a directory
 * @param unencrypted the original file to be encrypted
 * @exception java.io.IOException thrown when the operation fails,either because the encrypted
 * file already exists,or something Failed during encryption
 */
public void encrypt(File encrypted,KeyChainException;
项目:droid-stealth    文件:ICrypto.java   
public void decrypt(File encrypted,KeyChainException;

except: 和 except Exception as e 之间的区别:

except: 和 except Exception as e 之间的区别:

以下两个代码片段都做同样的事情。他们捕获每个异常并执行except:块中的代码

片段 1 -

try:    #some code that may throw an exceptionexcept:    #exception handling code

片段 2 -

try:    #some code that may throw an exceptionexcept Exception as e:    #exception handling code

两种构造的具体区别是什么?

答案1

小编典典

在第二个中,您可以访问异常对象的属性:

>>> def catch():...     try:...         asd()...     except Exception as e:...         print e.message, e.args... >>> catch()global name ''asd'' is not defined ("global name ''asd'' is not defined",)

但它没有捕获BaseException或系统退出异常SystemExitKeyboardInterrupt并且GeneratorExit

>>> def catch():...     try:...         raise BaseException()...     except Exception as e:...         print e.message, e.args... >>> catch()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 3, in catchBaseException

一个裸露的除外:

>>> def catch():...     try:...         raise BaseException()...     except:...         pass... >>> catch()>>>

有关详细信息,请参阅文档的内置异常部分和教程的错误和异常部分。

关于没有括号的“ raise exception”和“ raise exception”之间有区别吗?的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于asp.net-mvc – HttpResponseException和HttpException之间有什么区别?、c# – ArgumentException和Exception之间有什么区别?、com.facebook.crypto.exception.KeyChainException的实例源码、except: 和 except Exception as e 之间的区别:的相关知识,请在本站寻找。

本文标签: