这可能是一个关于异常处理的荒谬的Java问题,但我有一个UI actor(一个Android Activity),它从我的ContentProvider子类请求服务.当sd-card已满,sd-card缺失,网络i/o错误等时,子类想要抛出一些异常.但是,当我编写CP子类来抛出异常时,编译器提供添加异常CP班.显然,我不想修改基类,但我希望UI能够捕获子类的异常.
合理?这可能吗?如果没有,我的服务子类是否有更好的模式将其throwable对象返回到UI?
Throwable由于不同帖子中列出的原因,不建议捕捉.但是,有一个像下面这样的主要结构是否有意义?如果删除了Throwable行,则不会记录错误.
public static void main(String[] args) {
try {
launchMyApplication();
} catch (SomeCheckedException e) {
//recover if you can, log it if you can't
} catch (Exception e) {
//recover if you can (unlikely), log it if you can't
} catch (Throwable e) {
//Don't try to recover, but log it
logger.error("Oops: {}", e);
}
}
Run Code Online (Sandbox Code Playgroud) 我刚学习Java中的异常处理.我想知道的不是尝试说:
throw new Exception("My Message");
Run Code Online (Sandbox Code Playgroud)
和
String message=ex.getMessage();
System.out.println(message);
Run Code Online (Sandbox Code Playgroud)
看看下面的代码,
class ExceptionTest {
public static void main(String[] args) {
ExceptionTest t1=new ExceptionTest();
try {
t1.riskyMethod();//call the risky or exception throwing method
} catch(MyException myex) {
System.out.println("Exception has been thrown");
String message=myex.getMessage();//get the String passed during exception call
System.out.println("The message retrieved is "+message);
myex.printStackTrace();//prints name of exception and traces the function call stack
}
}//main ends
void riskyMethod() throws MyException {//a method that can throw an excpetion
int rand=(int)(Math.random()*10);///Math.rand return 0 …Run Code Online (Sandbox Code Playgroud) 我有以下两组代码
第一组代码如下:
public static void main(String[] args){
try {
main(null);
} catch (Throwable e) {
}
System.out.println("Value of args[0] is : "args[0]);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Value of args[0] is : db
Run Code Online (Sandbox Code Playgroud)
第二组代码如下:
public static void main(String[] args){
try {
main(null);
} catch (StackOverflowError e) {
}
System.out.println(args[0]);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Exception in thread "main" java.lang.NullPointerException
at com.way2learnonline.ui.Demo.main(Demo.java:16)
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我都传递一个命令行参数,即'db'.在第一组代码中,我在catch块中捕获Throwable,我可以访问命令行参数,即args[0](我可以在控制台中看到args [0]输出).
在第二组代码中,我正在捕获StackOverflowError,我无法访问args [0].它显示NullPointerException.
我无法理解Java的行为.
为什么我可以在第一种情况下访问args [0]以及为什么在第二种情况下args为null.
有人可以解释为什么java表现得像这样吗?
我有一个带@Aspect注释的类正在调用ProceedingJoinPoint#proceed()。此方法throws Throwable以及类的外观如下所示:
@Aspect
@Component
public class MyClass{
@Around("@annotation(myAnnotation)")
public Object myMethod(final ProceedingJoinPoint joinPoint) throws Throwable {
//some code here
try {
return joinPoint.proceed();
} finally {
//some more code here
}
}
}
Run Code Online (Sandbox Code Playgroud)
它是确定了myMehtod投掷Throwable在这种情况下,我必须调用另一个方法是throws Throwable?我应该避免抛出Throwable并以某种方式将其转换为Exceptionor Error吗?
无论哪种情况,我都想知道为什么。谢谢。
我在java-中有以下代码
@Override
public void run() {
logger.info("Thread Started:" + this.getName());
try {
runJob();
} catch( Throwable e) {
logger.error("Exception in running thread: " + this.getName() + ", restarting job", e);
run();
}
}
public void runJob() {
while(true) {
try {
// Work here
} catch(Exception e) {
// log the exception
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个代码实际上是否会在每种情况下保持线程活动,这只是恢复线程的方法吗?
这是我在阅读完所有答案后想到的另一种选择.让我知道,即使发生错误,这是一个永远保持线程活着的好方法:
@Override
public void run() {
logger.info("Thread Started:" + this.getName());
while(true) {
try {
runJob();
} catch( Throwable e) {
logger.error("Exception in running thread: …Run Code Online (Sandbox Code Playgroud) 将throwable/exception的整个堆栈跟踪转换为ByteBuffer(在Java中)的最有效方法是什么?
具体来说,我需要将整个异常记录到数据库中.Thread.currentThread().getStackTrace()返回StackTraceElement []数组的列表.
然后,Throwable类中有一个printStackTrace()方法?
我在其他问题中搜索这个问题,但仍然没有弄清楚 Throwable 的确切含义。阅读了一些关于它的文章(它的超级类bla bla bla),但仍然不知道如何实现它。忘了说我是java新手。任何建议将不胜感激:D
这是异常类:
class Exception {
private int pDen;
private int pMes;
private int kDen;
private int kMes;
public Exception(int pDen, int pMes, int kDen, int kMes) {
super();
this.pDen = pDen;
this.pMes = pMes;
this.kDen = kDen;
this.kMes = kMes;
}
public void message()
{
System.out.println("Isklucok");
}
public void promena()
{
int tmpDen = 0;
int tmpMes = 0;
tmpDen = pDen;
pDen = kDen;
kDen = tmpDen;
tmpMes = pMes;
pMes = kMes;
kMes = …Run Code Online (Sandbox Code Playgroud) 我有两个函数调用 Employee 和 Address DAO 类,我在其中检查员工姓名或地址是否已被使用
为了使检查和抛出异常通用,我创建了以下通用函数
checkOrElseThrow在CommonUtil.java
public static <R, C, T extends Throwable> R checkOrElseThrow(R rtn, C chk, Supplier<? extends T> ex) throws T
{
if (chk != null)
{
throw ex.get();
}
return rtn;
}
Run Code Online (Sandbox Code Playgroud)
上面的通用函数在EmployeeDAO.java和AddressDAO.java 中被调用,如下所示
checkAndReturnEmployee在EmployeeDAO.java
public Employee checkAndReturnEmployee(Employee employee) {
return checkOrElseThrow(
employee,
employee.getAddressName(),
() -> new EntityNotFoundException("Employee already in use for another address"));
}
Run Code Online (Sandbox Code Playgroud)
checkAndReturnAddress在AddressDAO.java
public Address checkAndReturnAddress(Address address) {
return checkOrElseThrow(
address, …Run Code Online (Sandbox Code Playgroud) 这就是我想要实现的:如果有一个方法a()调用 method b(),我想知道谁调用了 method b()。
public void a(){
b();//but it is not necessarily in the same class
}
public void b(){
String method = getCallerMethod();//returns 'a'
}
Run Code Online (Sandbox Code Playgroud)
现在,这可以在 Java 9+ 中使用 API 高效地实现StackWalker。在 Java 8 中,我可以使用Thread.currentThread().getStackTrace()or new Exception().getStackTrace(),但这两种方法都非常慢。我不需要整个堆栈跟踪,我只需要堆栈跟踪中的前一帧,并且只需要该帧中的方法名称(可能还有类名称)。
有没有办法在 Java 8 中有效地实现这一点?
java ×10
throwable ×10
exception ×4
aop ×1
aspectj ×1
constructor ×1
java-8 ×1
lambda ×1
performance ×1
stack-frame ×1
stack-trace ×1
subclass ×1
supplier ×1
throws ×1
try-catch ×1