"throws" and "annotation for exception" in Dalvik bytecode
Asked Answered
K

2

6

Why the byte code is generated as

 .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/FileNotFoundException;
        }
 .end annotation

rather than .throws Ljava/io/FileNotFoundException

if a method declares throws FileNotFoundException in the header in java code?

Koel answered 27/12, 2012 at 23:1 Comment(0)
G
6

The short answer is that there is no specific "throws" concept in the dex format. When a java classfile is converted to the dex format, a Throws annotation is added that contains this information.

Slightly longer answer:

The concept of a checked exception only matters at compile time, not at runtime. The dalvik virtual machine doesn't know about or care what exceptions your method can throw. As far as it is concerned, everything is an unchecked exception. It's the java compiler that enforces that checked exceptions are declared in your throws clause.

As such, it doesn't make sense to add a specific "throws" concept to the dex file. Instead, that information is stored using the more generic annotation feature.

It sounds like you are using something like dex2jar to convert a dex file back to a set of class file and then using jasmin on it. It's likely that dex2jar doesn't remap the Throws annotations from the dex file back to the Exception attribute in the classfile, although I haven't specifically checked whether that is the case.

Gristede answered 28/12, 2012 at 0:2 Comment(2)
I see your point. More contexts I can add in response to your reply are: 1. Yes, I need the compile time information, to know methods that can throw exceptions, rather than I hard coded myself. 2. The dex file is extracted from apk-tool. Then I use the dedexer(dedexer.sourceforge.net) to get the jasmin format of the classes. I just examine into the source code of it(in method addMethodAnnotation in JasminStyleCodeGenerator.java, it does deal with the throws and annotation at the same time but the output just shows that the method annotation is always outputed rather than throws.Koel
fwiw, you might be better off using baksmali. Although I'm obviously a tiny bit biased :). But baksmali has essentially the same behavior wrt to throws annotations (it shows it as an annotation).Gristede
B
1

dalvik.annotation.Throws appears on methods

A Throws annotation is attached to each method which is declared to throw one or more exception types.

At the bottom of this page.

Baruch answered 27/12, 2012 at 23:20 Comment(1)
But in this page: jasmin.sourceforge.net/guide.html, it says throws also serves the same role as annotation? The question is, are they the same?Koel

© 2022 - 2024 — McMap. All rights reserved.