GVKun编程网logo

except: 和 except Exception as e 之间的区别:(except与exception)

30

如果您对except:和exceptExceptionase之间的区别:和except与exception感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解except:和exceptExcept

如果您对except: 和 except Exception as e 之间的区别:except与exception感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解except: 和 except Exception as e 之间的区别:的各种细节,并对except与exception进行深入的分析,此外还有关于Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException、c# – ArgumentException和Exception之间有什么区别?、ClassNotFoundException: JspException、com.facebook.crypto.exception.KeyChainException的实例源码的实用技巧。

本文目录一览:

except: 和 except Exception as e 之间的区别:(except与exception)

except: 和 except Exception as e 之间的区别:(except与exception)

以下两个代码片段都做同样的事情。他们捕获每个异常并执行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()>>>

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

Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException

Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException

如何解决Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException?

我将 Azure Cosmos DB 4.0 与 MongoDB C# 驱动程序 2.10.4 结合使用。

大多数时候查询工作正常,但我遇到了这样的间歇性错误:

MongoDB.Driver.MongoConnectionException:向服务器发送消息时发生异常。 System.IO.IOException:无法将数据写入传输连接:远程主机强行关闭了现有连接。 System.Net.sockets.socketException: 一个现有的连接被远程主机强行关闭 在 System.Net.sockets.socket.BeginSend(... 在 System.Net.sockets.NetworkStream.BeginWrite --- 内部异常堆栈跟踪结束 --- 在 System.Net.sockets.NetworkStream.BeginWrite 在 System.Net.Security._SslStream.StartWriting 在 System.Net.Security._SslStream.ProcessWrite 在 System.Net.Security._SslStream.BeginWrite

发生该错误时,调用需要 10-25 秒才能失败。

我正在使用 @H_301_9@new MongoClient(MongoClientSettings.FromConnectionString(cnstr)) 构建 MongoClient,并且我使用的是带有这些参数 @H_301_9@?ssl=true&replicaset=globaldb&retrywrites=false 的连接字符串。

我尝试使用 @H_301_9@retryWrites=true(根据 Azure 支持建议),但这没有帮助。

我尝试了不同的设置,但都不起作用(@H_301_9@connect=direct、@H_301_9@maxIdleTimeMS=30000、@H_301_9@serverSelectionTimeout=5000ms、@H_301_9@socketTimeout=10000ms)。

导致这些异常的原因是什么?

解决方法

修复是设置/强制使用 TLS 1.2(基于 this Microsoft document):

//return new MongoClient(connectionString);
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.SslSettings = new SslSettings()
{
    EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
};
return new MongoClient(settings);

看起来虽然我的连接字符串有 ssl=true,但在某些服务器上还不够(错误是间歇性的)。 forcing TLS 1.2 通常可以修复相同的潜在错误,因此我认为在 Mongo 中它可能是相同的问题 - 它确实解决了问题。

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.

ClassNotFoundException: JspException

ClassNotFoundException: JspException

给这个问题耗上了, 我一定要把罪魁祸首找不来 找不出来不下班!!!
java.lang.ClassNotFoundException: JspException
	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
	java.lang.Class.getDeclaredMethods0(Native Method)
	java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
	java.lang.Class.getDeclaredMethods(Class.java:1791)
	java.beans.Introspector$1.run(Introspector.java:1287)
	java.security.AccessController.doPrivileged(Native Method)
	java.beans.Introspector.getPublicDeclaredMethods(Introspector.java:1285)
	java.beans.Introspector.getTargetMethodInfo(Introspector.java:1151)
	java.beans.Introspector.getBeanInfo(Introspector.java:402)
	java.beans.Introspector.getBeanInfo(Introspector.java:168)
	java.beans.Introspector.getBeanInfo(Introspector.java:229)
	java.beans.Introspector.<init>(Introspector.java:383)
	java.beans.Introspector.getBeanInfo(Introspector.java:168)
	org.apache.jasper.compiler.Generator$TagHandlerInfo.<init>(Generator.java:3943)
	org.apache.jasper.compiler.Generator$GenerateVisitor.getTagHandlerInfo(Generator.java:2209)
	org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1640)
	org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1539)
	org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
	org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428)
	org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2434)
	org.apache.jasper.compiler.Node$Root.accept(Node.java:475)
	org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
	org.apache.jasper.compiler.Generator.generate(Generator.java:3489)
	org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:250)
	org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
	org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
	org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
	org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
	clap.bnLog.filter.BnLogFilter.doFilter(BnLogFilter.java:34)
	clap.authority.filter.FunOrgAuFilterServlet.doFilter(FunOrgAuFilterServlet.java:33)
	clap.authority.filter.FilterServlet.doFilter(FilterServlet.java:91)
	clap.frames.i18n.filter.LocalFilter.doFilter(LocalFilter.java:71)
	clap.authority.xss.XSSSecurityFilter.doFilter(XSSSecurityFilter.java:68)
	clap.frames.web.SetEncodingFilter.doFilter(SetEncodingFilter.java:33)


===== 19:44 更新 =====

问题终于解决了,但是为什么导致这样的问题还是没能找出来。不过发现这个问题还是因为个人的操作失误导致的,  自作自受啊, 下不为例以后就张姿势了。

说一下我的环境和编译、部署的流程:

环境: 

项目没有使用ant之类的编译工具,运行项目也没有使用IDE内置的容器运行。

而是使用IDE编译代码,再单独启动容器跑程序。 

而问题就出现在编译阶段,因为在IDE中classpath有问题,导致IDE编译没有正确完成,当IDE classpath问题解决了,再启动容器没有报错,也可以正常访问页面。结论就是编译的代码不完整,而不是缺少jar文件或者冲突。一切都是自己咎由自取,活该!

为什么代码编译不完整运行时抛这么奇怪的错误,这个结果还没有弄清楚明白,估计这个要看容器的类加载时肿么了一个回事了,暂且不说了,以后有空估计也不会去看了。如果哪位无聊可以研究下。

终于搞定了,可以继续推进工作了。撤~~~ 


  

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与exception的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException、c# – ArgumentException和Exception之间有什么区别?、ClassNotFoundException: JspException、com.facebook.crypto.exception.KeyChainException的实例源码等相关知识的信息别忘了在本站进行查找喔。

本文标签: