在CLR(C#,VB.NET等使用的运行时)中,有一种方法可以在抛出未处理的异常时注册要调用的回调.
Java中有类似的东西吗?
我猜它可能是一些API,你传递一个对象,用一个方法实现一些接口.抛出异常并且catch堆栈上没有匹配时,运行时将调用已注册对象上的方法,并将传递异常对象.
这将允许程序员保存堆栈跟踪.它还允许它们调用System.exit,以停止finally仅针对未处理的异常执行的块.
更新1.
为了说明这一点,这里有一个C#示例:
// register custom handler for unhandled exceptions
AppDomain.CurrentDomain.UnhandledException += (sender, evt) =>
{
Console.WriteLine("unhandled exception");
Environment.FailFast(null);
};
try
{
throw new NullReferenceException();
}
finally
{
Console.WriteLine("finally is executing");
}
Run Code Online (Sandbox Code Playgroud)
关键是通过调用Environment.FailFast(null)我可以阻止finally块执行.
果然,在Windows 7上运行的.NET 3.5和4.0中,我看不到输出中的"finally is execution"字符串.但是如果我注释掉这个FailFast调用,那么我确实在输出中看到了这个字符串.
更新2.
基于到目前为止的答案,这是我尝试用Java重现它.
// register custom handler for unhandled exceptions
Thread.currentThread().setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
public void uncaughtException(
final Thread t, final Throwable e) {
System.out.println("Uncaught exception");
System.exit(0);
} …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
class SampleClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Execute Dispose!");
}
}
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
try
{
throw new Exception();
}
finally
{
sc.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行它时,它不会打印Execute Dispose!消息,为什么会这样?
更新:
如果我像这样更改了代码:
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
try
{
try
{
throw new Exception();
}
finally
{
sc.Dispose();
}
}
catch
{
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
它首先打印消息然后崩溃.
我的想法是,如果应用程序崩溃,它可以随意处理吗?
我知道这很简单,但我真的要学到更多东西.
我正在构建一个icosphere,我已经得到了代码的绘制部分,但我一直得到一个NullReferenceException是未处理的错误.我知道它指的是哪些代码,但我不知道实际上是什么错误或如何解决它.
这是类代码:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Icosahedron_Test
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Camera camera;
VertexPositionColor[] verts;
VertexBuffer vertexBuffer;
BasicEffect effect;
Matrix worldTranslation = Matrix.Identity;
Matrix worldRotation = Matrix.Identity;
int radius = 1; //planet radius
int refinement = 2; // number of times to refine …Run Code Online (Sandbox Code Playgroud) 在我的WPF应用程序中,一些用户得到"应用程序生成了一个无法处理的异常"错误.我已经实现了Application.DispatcherUnhandledException事件处理程序,但此事件不处理该异常.是否有可能在应用程序外发生异常导致关闭我的应用程序,可能是内存的东西?
我正在开发一个使用 plain 实现的项目threads。应用程序中的大多数预期异常都会得到处理,但是,在某些情况下,其中一个线程会引发意外异常,并且应用程序会崩溃(应用程序是基于两者的,I/O因此Client-Server实际上不可能处理所有异常)。
为了解决这个问题,我尝试定义一个全局变量UnhandledExceptionHandler,以便应用程序显示友好的消息而不是崩溃。这是我尝试过的:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// The rest of the startup logic goes here
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Utilities.DisplayUnhandledException((Exception)e.ExceptionObject);
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用。从未被CurrentDomain_UnhandledException调用过。不幸的是,我无法更改应用程序的结构,这意味着我无法使用任务并行库。我不明白为什么这不起作用。还有其他方法可以处理线程中抛出的异常吗?任何帮助表示赞赏。
我收到了拒绝访问权限的异常.我怎样才能解决这个问题?
这是一个例外:
System.UnauthorizedAccessException未处理HResult = -2147024891 Message =拒绝访问路径'c:\ message.txt'.
来源= mscorlib程序
这是代码:
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果我以管理员身份运行vs2012,它是否有效,但有没有办法或理由以普通用户身份执行?
这有效:
public static void WriteToFile(string s)
{
fs = new FileStream(@"C:\Users\KristjanBEstur\Documents\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
File.Delete(@"C:\Users\KristjanBEstur\Documents\message.txt");
}
Run Code Online (Sandbox Code Playgroud) 我知道有关检查异常的规则,但我无法解决这个问题.为什么第二种方法不能编译,但第一种方法呢?错误是最后一个throws语句中的"Unhandled exception type Exception".我能理解为什么我得到这个错误,但我不明白为什么第一种方法没问题,它应该有同样的问题?!
eclipse和intellij都显示相同的错误.
import java.util.concurrent.Callable;
public class ThrowableWeirdness {
public void doWithMetrics(String name, Runnable runnable) {
try {
runnable.run();
} catch (Throwable e) {
System.out.printf(name + ".failed");
throw e;
}
}
public <RET> RET doWithMetrics(String name, Callable<RET> runnable) {
try {
return runnable.call();
} catch (Throwable e) {
System.out.printf(name + ".failed");
throw e; // Compilation error on this line: unhandled exception
}
}
}
Run Code Online (Sandbox Code Playgroud)
你能解释一下这两种方法的区别吗?
在调用Pittney Bowes Geocoder服务时,我正在使用Polly来捕捉异常.我正在使用一个抛出MessageProcessingException的g1client库.如果抛出此异常,我已经将调用包装在Polly网络策略中以重试调用最多3次,但Visual Studio坚持异常为"User-Unhandled"我需要修改哪些内容才能处理此异常?我正在使用Visual Studio 2017社区版和C#4.6.1.
try
{
var networkPolicy = Policy
.Handle<MessageProcessingException>()
.Or<Exception>()
.WaitAndRetry(
3,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, context) =>
{
System.Diagnostics.Debug.WriteLine("Exception being retried" + exception);
});
geocoderResponse = networkPolicy.Execute(() => geocoderService.Process(geocoderRequest));
}
catch (MessageProcessingException ex)
{
log.Error("MessageProcessingException calling the Geocoder service", ex);
throw ex;
}
catch (Exception ex)
{
log.Error("Exception calling the Geocoder service", ex);
throw ex;
}
Run Code Online (Sandbox Code Playgroud)
错误消息是:
g1client.MessageProcessingException occurred
HResult=0x80131500
Message=Unable to read data from the transport connection: A connection attempt failed because …Run Code Online (Sandbox Code Playgroud) 我想AppDomain.FirstChanceException在我的WPF应用程序中实现,以便可选地记录发生,处理或不处理的每个异常.我不希望将这些例外记录到我为NLog配置的目标.是否有可能,在调用时Logger.Error(或任何Logger方法)使NLog只记录到一个特定的目标?